babylon.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. /** @hidden */
  190. this._bonesComputationForcedToCPU = false;
  191. this._uniformBuffersNames = {};
  192. this._isReady = false;
  193. this._compilationError = "";
  194. this.name = baseName;
  195. if (attributesNamesOrOptions.attributes) {
  196. var options = attributesNamesOrOptions;
  197. this._engine = uniformsNamesOrEngine;
  198. this._attributesNames = options.attributes;
  199. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  200. this._samplers = options.samplers.slice();
  201. this.defines = options.defines;
  202. this.onError = options.onError;
  203. this.onCompiled = options.onCompiled;
  204. this._fallbacks = options.fallbacks;
  205. this._indexParameters = options.indexParameters;
  206. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  207. if (options.uniformBuffersNames) {
  208. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  209. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  210. }
  211. }
  212. }
  213. else {
  214. this._engine = engine;
  215. this.defines = defines;
  216. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  217. this._samplers = samplers ? samplers.slice() : [];
  218. this._attributesNames = attributesNamesOrOptions;
  219. this.onError = onError;
  220. this.onCompiled = onCompiled;
  221. this._indexParameters = indexParameters;
  222. this._fallbacks = fallbacks;
  223. }
  224. this.uniqueId = Effect._uniqueIdSeed++;
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. this._loadVertexShader(vertexSource, function (vertexCode) {
  246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  247. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  250. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  251. if (baseName) {
  252. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  253. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  254. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  255. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  256. }
  257. else {
  258. _this._vertexSourceCode = migratedVertexCode;
  259. _this._fragmentSourceCode = migratedFragmentCode;
  260. }
  261. _this._prepareEffect();
  262. });
  263. });
  264. });
  265. });
  266. });
  267. });
  268. }
  269. Object.defineProperty(Effect.prototype, "key", {
  270. /**
  271. * Unique key for this effect
  272. */
  273. get: function () {
  274. return this._key;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. /**
  280. * If the effect has been compiled and prepared.
  281. * @returns if the effect is compiled and prepared.
  282. */
  283. Effect.prototype.isReady = function () {
  284. return this._isReady;
  285. };
  286. /**
  287. * The engine the effect was initialized with.
  288. * @returns the engine.
  289. */
  290. Effect.prototype.getEngine = function () {
  291. return this._engine;
  292. };
  293. /**
  294. * The compiled webGL program for the effect
  295. * @returns the webGL program.
  296. */
  297. Effect.prototype.getProgram = function () {
  298. return this._program;
  299. };
  300. /**
  301. * The set of names of attribute variables for the shader.
  302. * @returns An array of attribute names.
  303. */
  304. Effect.prototype.getAttributesNames = function () {
  305. return this._attributesNames;
  306. };
  307. /**
  308. * Returns the attribute at the given index.
  309. * @param index The index of the attribute.
  310. * @returns The location of the attribute.
  311. */
  312. Effect.prototype.getAttributeLocation = function (index) {
  313. return this._attributes[index];
  314. };
  315. /**
  316. * Returns the attribute based on the name of the variable.
  317. * @param name of the attribute to look up.
  318. * @returns the attribute location.
  319. */
  320. Effect.prototype.getAttributeLocationByName = function (name) {
  321. var index = this._attributesNames.indexOf(name);
  322. return this._attributes[index];
  323. };
  324. /**
  325. * The number of attributes.
  326. * @returns the numnber of attributes.
  327. */
  328. Effect.prototype.getAttributesCount = function () {
  329. return this._attributes.length;
  330. };
  331. /**
  332. * Gets the index of a uniform variable.
  333. * @param uniformName of the uniform to look up.
  334. * @returns the index.
  335. */
  336. Effect.prototype.getUniformIndex = function (uniformName) {
  337. return this._uniformsNames.indexOf(uniformName);
  338. };
  339. /**
  340. * Returns the attribute based on the name of the variable.
  341. * @param uniformName of the uniform to look up.
  342. * @returns the location of the uniform.
  343. */
  344. Effect.prototype.getUniform = function (uniformName) {
  345. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  346. };
  347. /**
  348. * Returns an array of sampler variable names
  349. * @returns The array of sampler variable neames.
  350. */
  351. Effect.prototype.getSamplers = function () {
  352. return this._samplers;
  353. };
  354. /**
  355. * The error from the last compilation.
  356. * @returns the error string.
  357. */
  358. Effect.prototype.getCompilationError = function () {
  359. return this._compilationError;
  360. };
  361. /**
  362. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  363. * @param func The callback to be used.
  364. */
  365. Effect.prototype.executeWhenCompiled = function (func) {
  366. if (this.isReady()) {
  367. func(this);
  368. return;
  369. }
  370. this.onCompileObservable.add(function (effect) {
  371. func(effect);
  372. });
  373. };
  374. /** @hidden */
  375. Effect.prototype._loadVertexShader = function (vertex, callback) {
  376. if (BABYLON.Tools.IsWindowObjectExist()) {
  377. // DOM element ?
  378. if (vertex instanceof HTMLElement) {
  379. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  380. callback(vertexCode);
  381. return;
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (vertex.substr(0, 7) === "base64:") {
  386. var vertexBinary = window.atob(vertex.substr(7));
  387. callback(vertexBinary);
  388. return;
  389. }
  390. // Is in local store ?
  391. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  392. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  393. return;
  394. }
  395. var vertexShaderUrl;
  396. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  397. vertexShaderUrl = vertex;
  398. }
  399. else {
  400. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  401. }
  402. // Vertex shader
  403. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  404. };
  405. /** @hidden */
  406. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  407. if (BABYLON.Tools.IsWindowObjectExist()) {
  408. // DOM element ?
  409. if (fragment instanceof HTMLElement) {
  410. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  411. callback(fragmentCode);
  412. return;
  413. }
  414. }
  415. // Base64 encoded ?
  416. if (fragment.substr(0, 7) === "base64:") {
  417. var fragmentBinary = window.atob(fragment.substr(7));
  418. callback(fragmentBinary);
  419. return;
  420. }
  421. // Is in local store ?
  422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  424. return;
  425. }
  426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  428. return;
  429. }
  430. var fragmentShaderUrl;
  431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  432. fragmentShaderUrl = fragment;
  433. }
  434. else {
  435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  436. }
  437. // Fragment shader
  438. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  439. };
  440. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  441. // Rebuild shaders source code
  442. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  443. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  444. vertexCode = prefix + vertexCode;
  445. fragmentCode = prefix + fragmentCode;
  446. // Number lines of shaders source code
  447. var i = 2;
  448. var regex = /\n/gm;
  449. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  450. i = 2;
  451. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. // Dump shaders name and formatted source code
  453. if (this.name.vertexElement) {
  454. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  455. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  456. }
  457. else if (this.name.vertex) {
  458. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  459. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  460. }
  461. else {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  464. }
  465. };
  466. ;
  467. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  468. var preparedSourceCode = this._processPrecision(sourceCode);
  469. if (this._engine.webGLVersion == 1) {
  470. callback(preparedSourceCode);
  471. return;
  472. }
  473. // Already converted
  474. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  475. callback(preparedSourceCode.replace("#version 300 es", ""));
  476. return;
  477. }
  478. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  479. // Remove extensions
  480. // #extension GL_OES_standard_derivatives : enable
  481. // #extension GL_EXT_shader_texture_lod : enable
  482. // #extension GL_EXT_frag_depth : enable
  483. // #extension GL_EXT_draw_buffers : require
  484. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  485. var result = preparedSourceCode.replace(regex, "");
  486. // Migrate to GLSL v300
  487. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  488. result = result.replace(/attribute[ \t]/g, "in ");
  489. result = result.replace(/[ \t]attribute/g, " in");
  490. if (isFragment) {
  491. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  492. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/texture2D\s*\(/g, "texture(");
  494. result = result.replace(/textureCube\s*\(/g, "texture(");
  495. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  496. result = result.replace(/gl_FragColor/g, "glFragColor");
  497. result = result.replace(/gl_FragData/g, "glFragData");
  498. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  499. }
  500. callback(result);
  501. };
  502. Effect.prototype._processIncludes = function (sourceCode, callback) {
  503. var _this = this;
  504. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  505. var match = regex.exec(sourceCode);
  506. var returnValue = new String(sourceCode);
  507. while (match != null) {
  508. var includeFile = match[1];
  509. // Uniform declaration
  510. if (includeFile.indexOf("__decl__") !== -1) {
  511. includeFile = includeFile.replace(/__decl__/, "");
  512. if (this._engine.supportsUniformBuffers) {
  513. includeFile = includeFile.replace(/Vertex/, "Ubo");
  514. includeFile = includeFile.replace(/Fragment/, "Ubo");
  515. }
  516. includeFile = includeFile + "Declaration";
  517. }
  518. if (Effect.IncludesShadersStore[includeFile]) {
  519. // Substitution
  520. var includeContent = Effect.IncludesShadersStore[includeFile];
  521. if (match[2]) {
  522. var splits = match[3].split(",");
  523. for (var index = 0; index < splits.length; index += 2) {
  524. var source = new RegExp(splits[index], "g");
  525. var dest = splits[index + 1];
  526. includeContent = includeContent.replace(source, dest);
  527. }
  528. }
  529. if (match[4]) {
  530. var indexString = match[5];
  531. if (indexString.indexOf("..") !== -1) {
  532. var indexSplits = indexString.split("..");
  533. var minIndex = parseInt(indexSplits[0]);
  534. var maxIndex = parseInt(indexSplits[1]);
  535. var sourceIncludeContent = includeContent.slice(0);
  536. includeContent = "";
  537. if (isNaN(maxIndex)) {
  538. maxIndex = this._indexParameters[indexSplits[1]];
  539. }
  540. for (var i = minIndex; i < maxIndex; i++) {
  541. if (!this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  548. }
  549. }
  550. else {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent = includeContent.replace(/\{X\}/g, indexString);
  558. }
  559. }
  560. // Replace
  561. returnValue = returnValue.replace(match[0], includeContent);
  562. }
  563. else {
  564. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  565. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  566. Effect.IncludesShadersStore[includeFile] = fileContent;
  567. _this._processIncludes(returnValue, callback);
  568. });
  569. return;
  570. }
  571. match = regex.exec(sourceCode);
  572. }
  573. callback(returnValue);
  574. };
  575. Effect.prototype._processPrecision = function (source) {
  576. if (source.indexOf("precision highp float") === -1) {
  577. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  578. source = "precision mediump float;\n" + source;
  579. }
  580. else {
  581. source = "precision highp float;\n" + source;
  582. }
  583. }
  584. else {
  585. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  586. source = source.replace("precision highp float", "precision mediump float");
  587. }
  588. }
  589. return source;
  590. };
  591. /**
  592. * Recompiles the webGL program
  593. * @param vertexSourceCode The source code for the vertex shader.
  594. * @param fragmentSourceCode The source code for the fragment shader.
  595. * @param onCompiled Callback called when completed.
  596. * @param onError Callback called on error.
  597. */
  598. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  599. var _this = this;
  600. this._isReady = false;
  601. this._vertexSourceCodeOverride = vertexSourceCode;
  602. this._fragmentSourceCodeOverride = fragmentSourceCode;
  603. this.onError = function (effect, error) {
  604. if (onError) {
  605. onError(error);
  606. }
  607. };
  608. this.onCompiled = function () {
  609. var scenes = _this.getEngine().scenes;
  610. for (var i = 0; i < scenes.length; i++) {
  611. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  612. }
  613. if (onCompiled) {
  614. onCompiled(_this._program);
  615. }
  616. };
  617. this._fallbacks = null;
  618. this._prepareEffect();
  619. };
  620. /**
  621. * Gets the uniform locations of the the specified variable names
  622. * @param names THe names of the variables to lookup.
  623. * @returns Array of locations in the same order as variable names.
  624. */
  625. Effect.prototype.getSpecificUniformLocations = function (names) {
  626. var engine = this._engine;
  627. return engine.getUniforms(this._program, names);
  628. };
  629. /**
  630. * Prepares the effect
  631. */
  632. Effect.prototype._prepareEffect = function () {
  633. var attributesNames = this._attributesNames;
  634. var defines = this.defines;
  635. var fallbacks = this._fallbacks;
  636. this._valueCache = {};
  637. var previousProgram = this._program;
  638. try {
  639. var engine = this._engine;
  640. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  641. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  642. }
  643. else {
  644. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  645. }
  646. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  647. if (engine.supportsUniformBuffers) {
  648. for (var name in this._uniformBuffersNames) {
  649. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  650. }
  651. }
  652. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  653. this._attributes = engine.getAttributes(this._program, attributesNames);
  654. var index;
  655. for (index = 0; index < this._samplers.length; index++) {
  656. var sampler = this.getUniform(this._samplers[index]);
  657. if (sampler == null) {
  658. this._samplers.splice(index, 1);
  659. index--;
  660. }
  661. }
  662. engine.bindSamplers(this);
  663. this._compilationError = "";
  664. this._isReady = true;
  665. if (this.onCompiled) {
  666. this.onCompiled(this);
  667. }
  668. this.onCompileObservable.notifyObservers(this);
  669. this.onCompileObservable.clear();
  670. // Unbind mesh reference in fallbacks
  671. if (this._fallbacks) {
  672. this._fallbacks.unBindMesh();
  673. }
  674. if (previousProgram) {
  675. this.getEngine()._deleteProgram(previousProgram);
  676. }
  677. }
  678. catch (e) {
  679. this._compilationError = e.message;
  680. // Let's go through fallbacks then
  681. BABYLON.Tools.Error("Unable to compile effect:");
  682. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  683. return " " + uniform;
  684. }));
  685. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  686. return " " + attribute;
  687. }));
  688. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  689. BABYLON.Tools.Error("Error: " + this._compilationError);
  690. if (previousProgram) {
  691. this._program = previousProgram;
  692. this._isReady = true;
  693. if (this.onError) {
  694. this.onError(this, this._compilationError);
  695. }
  696. this.onErrorObservable.notifyObservers(this);
  697. }
  698. if (fallbacks && fallbacks.isMoreFallbacks) {
  699. BABYLON.Tools.Error("Trying next fallback.");
  700. this.defines = fallbacks.reduce(this.defines, this);
  701. this._prepareEffect();
  702. }
  703. else { // Sorry we did everything we can
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. this.onErrorObservable.clear();
  709. // Unbind mesh reference in fallbacks
  710. if (this._fallbacks) {
  711. this._fallbacks.unBindMesh();
  712. }
  713. }
  714. }
  715. };
  716. Object.defineProperty(Effect.prototype, "isSupported", {
  717. /**
  718. * Checks if the effect is supported. (Must be called after compilation)
  719. */
  720. get: function () {
  721. return this._compilationError === "";
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. /**
  727. * Binds a texture to the engine to be used as output of the shader.
  728. * @param channel Name of the output variable.
  729. * @param texture Texture to bind.
  730. */
  731. Effect.prototype._bindTexture = function (channel, texture) {
  732. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  733. };
  734. /**
  735. * Sets a texture on the engine to be used in the shader.
  736. * @param channel Name of the sampler variable.
  737. * @param texture Texture to set.
  738. */
  739. Effect.prototype.setTexture = function (channel, texture) {
  740. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  741. };
  742. /**
  743. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  744. * @param channel Name of the sampler variable.
  745. * @param texture Texture to set.
  746. */
  747. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  748. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  749. };
  750. /**
  751. * Sets an array of textures on the engine to be used in the shader.
  752. * @param channel Name of the variable.
  753. * @param textures Textures to set.
  754. */
  755. Effect.prototype.setTextureArray = function (channel, textures) {
  756. if (this._samplers.indexOf(channel + "Ex") === -1) {
  757. var initialPos = this._samplers.indexOf(channel);
  758. for (var index = 1; index < textures.length; index++) {
  759. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  760. }
  761. }
  762. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  763. };
  764. /**
  765. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  766. * @param channel Name of the sampler variable.
  767. * @param postProcess Post process to get the input texture from.
  768. */
  769. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  770. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  771. };
  772. /**
  773. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  774. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the output texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /** @hidden */
  782. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  783. var cache = this._valueCache[uniformName];
  784. var flag = matrix.updateFlag;
  785. if (cache !== undefined && cache === flag) {
  786. return false;
  787. }
  788. this._valueCache[uniformName] = flag;
  789. return true;
  790. };
  791. /** @hidden */
  792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  793. var cache = this._valueCache[uniformName];
  794. if (!cache) {
  795. cache = [x, y];
  796. this._valueCache[uniformName] = cache;
  797. return true;
  798. }
  799. var changed = false;
  800. if (cache[0] !== x) {
  801. cache[0] = x;
  802. changed = true;
  803. }
  804. if (cache[1] !== y) {
  805. cache[1] = y;
  806. changed = true;
  807. }
  808. return changed;
  809. };
  810. /** @hidden */
  811. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  812. var cache = this._valueCache[uniformName];
  813. if (!cache) {
  814. cache = [x, y, z];
  815. this._valueCache[uniformName] = cache;
  816. return true;
  817. }
  818. var changed = false;
  819. if (cache[0] !== x) {
  820. cache[0] = x;
  821. changed = true;
  822. }
  823. if (cache[1] !== y) {
  824. cache[1] = y;
  825. changed = true;
  826. }
  827. if (cache[2] !== z) {
  828. cache[2] = z;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /** @hidden */
  834. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  835. var cache = this._valueCache[uniformName];
  836. if (!cache) {
  837. cache = [x, y, z, w];
  838. this._valueCache[uniformName] = cache;
  839. return true;
  840. }
  841. var changed = false;
  842. if (cache[0] !== x) {
  843. cache[0] = x;
  844. changed = true;
  845. }
  846. if (cache[1] !== y) {
  847. cache[1] = y;
  848. changed = true;
  849. }
  850. if (cache[2] !== z) {
  851. cache[2] = z;
  852. changed = true;
  853. }
  854. if (cache[3] !== w) {
  855. cache[3] = w;
  856. changed = true;
  857. }
  858. return changed;
  859. };
  860. /**
  861. * Binds a buffer to a uniform.
  862. * @param buffer Buffer to bind.
  863. * @param name Name of the uniform variable to bind to.
  864. */
  865. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  866. var bufferName = this._uniformBuffersNames[name];
  867. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  868. return;
  869. }
  870. Effect._baseCache[bufferName] = buffer;
  871. this._engine.bindUniformBufferBase(buffer, bufferName);
  872. };
  873. /**
  874. * Binds block to a uniform.
  875. * @param blockName Name of the block to bind.
  876. * @param index Index to bind.
  877. */
  878. Effect.prototype.bindUniformBlock = function (blockName, index) {
  879. this._engine.bindUniformBlock(this._program, blockName, index);
  880. };
  881. /**
  882. * Sets an interger value on a uniform variable.
  883. * @param uniformName Name of the variable.
  884. * @param value Value to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setInt = function (uniformName, value) {
  888. var cache = this._valueCache[uniformName];
  889. if (cache !== undefined && cache === value)
  890. return this;
  891. this._valueCache[uniformName] = value;
  892. this._engine.setInt(this.getUniform(uniformName), value);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array on a uniform variable.
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray2 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray2(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array on a uniform variable.
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray2 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray2(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setArray3 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setArray3(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setArray4 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setArray4(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * Sets matrices on a uniform variable.
  1029. * @param uniformName Name of the variable.
  1030. * @param matrices matrices to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1034. if (!matrices) {
  1035. return this;
  1036. }
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets matrix on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param matrix matrix to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1048. if (this._cacheMatrix(uniformName, matrix)) {
  1049. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1050. }
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1066. * @param uniformName Name of the variable.
  1067. * @param matrix matrix to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1071. this._valueCache[uniformName] = null;
  1072. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a float on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param value value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setFloat = function (uniformName, value) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === value)
  1084. return this;
  1085. this._valueCache[uniformName] = value;
  1086. this._engine.setFloat(this.getUniform(uniformName), value);
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a boolean on a uniform variable.
  1091. * @param uniformName Name of the variable.
  1092. * @param bool value to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setBool = function (uniformName, bool) {
  1096. var cache = this._valueCache[uniformName];
  1097. if (cache !== undefined && cache === bool)
  1098. return this;
  1099. this._valueCache[uniformName] = bool;
  1100. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a Vector2 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param vector2 vector2 to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1110. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a float2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param x First float in float2.
  1119. * @param y Second float in float2.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1123. if (this._cacheFloat2(uniformName, x, y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a Vector3 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param vector3 Value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1135. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1136. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a float3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param x First float in float3.
  1144. * @param y Second float in float3.
  1145. * @param z Third float in float3.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1149. if (this._cacheFloat3(uniformName, x, y, z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Vector4 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param vector4 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1161. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a float4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param x First float in float4.
  1170. * @param y Second float in float4.
  1171. * @param z Third float in float4.
  1172. * @param w Fourth float in float4.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1176. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1177. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1178. }
  1179. return this;
  1180. };
  1181. /**
  1182. * Sets a Color3 on a uniform variable.
  1183. * @param uniformName Name of the variable.
  1184. * @param color3 Value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor3 = function (uniformName, color3) {
  1188. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1189. this._engine.setColor3(this.getUniform(uniformName), color3);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @param alpha Alpha value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1201. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1202. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable
  1208. * @param uniformName defines the name of the variable
  1209. * @param color4 defines the value to be set
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1213. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1214. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Resets the cache of effects.
  1220. */
  1221. Effect.ResetCache = function () {
  1222. Effect._baseCache = {};
  1223. };
  1224. Effect._uniqueIdSeed = 0;
  1225. Effect._baseCache = {};
  1226. /**
  1227. * Store of each shader (The can be looked up using effect.key)
  1228. */
  1229. Effect.ShadersStore = {};
  1230. /**
  1231. * Store of each included file for a shader (The can be looked up using effect.key)
  1232. */
  1233. Effect.IncludesShadersStore = {};
  1234. return Effect;
  1235. }());
  1236. BABYLON.Effect = Effect;
  1237. })(BABYLON || (BABYLON = {}));
  1238. //# sourceMappingURL=babylon.effect.js.map
  1239. //# sourceMappingURL=babylon.types.js.map
  1240. var BABYLON;
  1241. (function (BABYLON) {
  1242. var KeyboardEventTypes = /** @class */ (function () {
  1243. function KeyboardEventTypes() {
  1244. }
  1245. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1246. get: function () {
  1247. return KeyboardEventTypes._KEYDOWN;
  1248. },
  1249. enumerable: true,
  1250. configurable: true
  1251. });
  1252. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1253. get: function () {
  1254. return KeyboardEventTypes._KEYUP;
  1255. },
  1256. enumerable: true,
  1257. configurable: true
  1258. });
  1259. KeyboardEventTypes._KEYDOWN = 0x01;
  1260. KeyboardEventTypes._KEYUP = 0x02;
  1261. return KeyboardEventTypes;
  1262. }());
  1263. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1264. var KeyboardInfo = /** @class */ (function () {
  1265. function KeyboardInfo(type, event) {
  1266. this.type = type;
  1267. this.event = event;
  1268. }
  1269. return KeyboardInfo;
  1270. }());
  1271. BABYLON.KeyboardInfo = KeyboardInfo;
  1272. /**
  1273. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1274. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1275. */
  1276. var KeyboardInfoPre = /** @class */ (function (_super) {
  1277. __extends(KeyboardInfoPre, _super);
  1278. function KeyboardInfoPre(type, event) {
  1279. var _this = _super.call(this, type, event) || this;
  1280. _this.skipOnPointerObservable = false;
  1281. return _this;
  1282. }
  1283. return KeyboardInfoPre;
  1284. }(KeyboardInfo));
  1285. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1286. })(BABYLON || (BABYLON = {}));
  1287. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1288. var BABYLON;
  1289. (function (BABYLON) {
  1290. var PointerEventTypes = /** @class */ (function () {
  1291. function PointerEventTypes() {
  1292. }
  1293. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERDOWN;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERUP;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERMOVE;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERWHEEL;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1322. get: function () {
  1323. return PointerEventTypes._POINTERPICK;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1329. get: function () {
  1330. return PointerEventTypes._POINTERTAP;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1336. get: function () {
  1337. return PointerEventTypes._POINTERDOUBLETAP;
  1338. },
  1339. enumerable: true,
  1340. configurable: true
  1341. });
  1342. PointerEventTypes._POINTERDOWN = 0x01;
  1343. PointerEventTypes._POINTERUP = 0x02;
  1344. PointerEventTypes._POINTERMOVE = 0x04;
  1345. PointerEventTypes._POINTERWHEEL = 0x08;
  1346. PointerEventTypes._POINTERPICK = 0x10;
  1347. PointerEventTypes._POINTERTAP = 0x20;
  1348. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1349. return PointerEventTypes;
  1350. }());
  1351. BABYLON.PointerEventTypes = PointerEventTypes;
  1352. var PointerInfoBase = /** @class */ (function () {
  1353. function PointerInfoBase(type, event) {
  1354. this.type = type;
  1355. this.event = event;
  1356. }
  1357. return PointerInfoBase;
  1358. }());
  1359. BABYLON.PointerInfoBase = PointerInfoBase;
  1360. /**
  1361. * This class is used to store pointer related info for the onPrePointerObservable event.
  1362. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1363. */
  1364. var PointerInfoPre = /** @class */ (function (_super) {
  1365. __extends(PointerInfoPre, _super);
  1366. function PointerInfoPre(type, event, localX, localY) {
  1367. var _this = _super.call(this, type, event) || this;
  1368. /**
  1369. * Ray from a pointer if availible (eg. 6dof controller)
  1370. */
  1371. _this.ray = null;
  1372. _this.skipOnPointerObservable = false;
  1373. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1374. return _this;
  1375. }
  1376. return PointerInfoPre;
  1377. }(PointerInfoBase));
  1378. BABYLON.PointerInfoPre = PointerInfoPre;
  1379. /**
  1380. * This type contains all the data related to a pointer event in Babylon.js.
  1381. * 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.
  1382. */
  1383. var PointerInfo = /** @class */ (function (_super) {
  1384. __extends(PointerInfo, _super);
  1385. function PointerInfo(type, event, pickInfo) {
  1386. var _this = _super.call(this, type, event) || this;
  1387. _this.pickInfo = pickInfo;
  1388. return _this;
  1389. }
  1390. return PointerInfo;
  1391. }(PointerInfoBase));
  1392. BABYLON.PointerInfo = PointerInfo;
  1393. })(BABYLON || (BABYLON = {}));
  1394. //# sourceMappingURL=babylon.pointerEvents.js.map
  1395. var BABYLON;
  1396. (function (BABYLON) {
  1397. BABYLON.ToGammaSpace = 1 / 2.2;
  1398. BABYLON.ToLinearSpace = 2.2;
  1399. BABYLON.Epsilon = 0.001;
  1400. /**
  1401. * Class used to hold a RBG color
  1402. */
  1403. var Color3 = /** @class */ (function () {
  1404. /**
  1405. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1406. * @param r defines the red component (between 0 and 1, default is 0)
  1407. * @param g defines the green component (between 0 and 1, default is 0)
  1408. * @param b defines the blue component (between 0 and 1, default is 0)
  1409. */
  1410. function Color3(
  1411. /**
  1412. * Defines the red component (between 0 and 1, default is 0)
  1413. */
  1414. r,
  1415. /**
  1416. * Defines the green component (between 0 and 1, default is 0)
  1417. */
  1418. g,
  1419. /**
  1420. * Defines the blue component (between 0 and 1, default is 0)
  1421. */
  1422. b) {
  1423. if (r === void 0) { r = 0; }
  1424. if (g === void 0) { g = 0; }
  1425. if (b === void 0) { b = 0; }
  1426. this.r = r;
  1427. this.g = g;
  1428. this.b = b;
  1429. }
  1430. /**
  1431. * Creates a string with the Color3 current values
  1432. * @returns the string representation of the Color3 object
  1433. */
  1434. Color3.prototype.toString = function () {
  1435. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1436. };
  1437. /**
  1438. * Returns the string "Color3"
  1439. * @returns "Color3"
  1440. */
  1441. Color3.prototype.getClassName = function () {
  1442. return "Color3";
  1443. };
  1444. /**
  1445. * Compute the Color3 hash code
  1446. * @returns an unique number that can be used to hash Color3 objects
  1447. */
  1448. Color3.prototype.getHashCode = function () {
  1449. var hash = this.r || 0;
  1450. hash = (hash * 397) ^ (this.g || 0);
  1451. hash = (hash * 397) ^ (this.b || 0);
  1452. return hash;
  1453. };
  1454. // Operators
  1455. /**
  1456. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1457. * @param array defines the array where to store the r,g,b components
  1458. * @param index defines an optional index in the target array to define where to start storing values
  1459. * @returns the current Color3 object
  1460. */
  1461. Color3.prototype.toArray = function (array, index) {
  1462. if (index === undefined) {
  1463. index = 0;
  1464. }
  1465. array[index] = this.r;
  1466. array[index + 1] = this.g;
  1467. array[index + 2] = this.b;
  1468. return this;
  1469. };
  1470. /**
  1471. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1472. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1473. * @returns a new {BABYLON.Color4} object
  1474. */
  1475. Color3.prototype.toColor4 = function (alpha) {
  1476. if (alpha === void 0) { alpha = 1; }
  1477. return new Color4(this.r, this.g, this.b, alpha);
  1478. };
  1479. /**
  1480. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1481. * @returns the new array
  1482. */
  1483. Color3.prototype.asArray = function () {
  1484. var result = new Array();
  1485. this.toArray(result, 0);
  1486. return result;
  1487. };
  1488. /**
  1489. * Returns the luminance value
  1490. * @returns a float value
  1491. */
  1492. Color3.prototype.toLuminance = function () {
  1493. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1494. };
  1495. /**
  1496. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1497. * @param otherColor defines the second operand
  1498. * @returns the new Color3 object
  1499. */
  1500. Color3.prototype.multiply = function (otherColor) {
  1501. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1502. };
  1503. /**
  1504. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1505. * @param otherColor defines the second operand
  1506. * @param result defines the Color3 object where to store the result
  1507. * @returns the current Color3
  1508. */
  1509. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1510. result.r = this.r * otherColor.r;
  1511. result.g = this.g * otherColor.g;
  1512. result.b = this.b * otherColor.b;
  1513. return this;
  1514. };
  1515. /**
  1516. * Determines equality between Color3 objects
  1517. * @param otherColor defines the second operand
  1518. * @returns true if the rgb values are equal to the given ones
  1519. */
  1520. Color3.prototype.equals = function (otherColor) {
  1521. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1522. };
  1523. /**
  1524. * Determines equality between the current Color3 object and a set of r,b,g values
  1525. * @param r defines the red component to check
  1526. * @param g defines the green component to check
  1527. * @param b defines the blue component to check
  1528. * @returns true if the rgb values are equal to the given ones
  1529. */
  1530. Color3.prototype.equalsFloats = function (r, g, b) {
  1531. return this.r === r && this.g === g && this.b === b;
  1532. };
  1533. /**
  1534. * Multiplies in place each rgb value by scale
  1535. * @param scale defines the scaling factor
  1536. * @returns the updated Color3
  1537. */
  1538. Color3.prototype.scale = function (scale) {
  1539. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1540. };
  1541. /**
  1542. * Multiplies the rgb values by scale and stores the result into "result"
  1543. * @param scale defines the scaling factor
  1544. * @param result defines the Color3 object where to store the result
  1545. * @returns the unmodified current Color3
  1546. */
  1547. Color3.prototype.scaleToRef = function (scale, result) {
  1548. result.r = this.r * scale;
  1549. result.g = this.g * scale;
  1550. result.b = this.b * scale;
  1551. return this;
  1552. };
  1553. /**
  1554. * Scale the current Color3 values by a factor and add the result to a given Color3
  1555. * @param scale defines the scale factor
  1556. * @param result defines color to store the result into
  1557. * @returns the unmodified current Color3
  1558. */
  1559. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1560. result.r += this.r * scale;
  1561. result.g += this.g * scale;
  1562. result.b += this.b * scale;
  1563. return this;
  1564. };
  1565. /**
  1566. * Clamps the rgb values by the min and max values and stores the result into "result"
  1567. * @param min defines minimum clamping value (default is 0)
  1568. * @param max defines maximum clamping value (default is 1)
  1569. * @param result defines color to store the result into
  1570. * @returns the original Color3
  1571. */
  1572. Color3.prototype.clampToRef = function (min, max, result) {
  1573. if (min === void 0) { min = 0; }
  1574. if (max === void 0) { max = 1; }
  1575. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1576. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1577. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1578. return this;
  1579. };
  1580. /**
  1581. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1582. * @param otherColor defines the second operand
  1583. * @returns the new Color3
  1584. */
  1585. Color3.prototype.add = function (otherColor) {
  1586. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1587. };
  1588. /**
  1589. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1590. * @param otherColor defines the second operand
  1591. * @param result defines Color3 object to store the result into
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.addToRef = function (otherColor, result) {
  1595. result.r = this.r + otherColor.r;
  1596. result.g = this.g + otherColor.g;
  1597. result.b = this.b + otherColor.b;
  1598. return this;
  1599. };
  1600. /**
  1601. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1602. * @param otherColor defines the second operand
  1603. * @returns the new Color3
  1604. */
  1605. Color3.prototype.subtract = function (otherColor) {
  1606. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1607. };
  1608. /**
  1609. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1610. * @param otherColor defines the second operand
  1611. * @param result defines Color3 object to store the result into
  1612. * @returns the unmodified current Color3
  1613. */
  1614. Color3.prototype.subtractToRef = function (otherColor, result) {
  1615. result.r = this.r - otherColor.r;
  1616. result.g = this.g - otherColor.g;
  1617. result.b = this.b - otherColor.b;
  1618. return this;
  1619. };
  1620. /**
  1621. * Copy the current object
  1622. * @returns a new Color3 copied the current one
  1623. */
  1624. Color3.prototype.clone = function () {
  1625. return new Color3(this.r, this.g, this.b);
  1626. };
  1627. /**
  1628. * Copies the rgb values from the source in the current Color3
  1629. * @param source defines the source Color3 object
  1630. * @returns the updated Color3 object
  1631. */
  1632. Color3.prototype.copyFrom = function (source) {
  1633. this.r = source.r;
  1634. this.g = source.g;
  1635. this.b = source.b;
  1636. return this;
  1637. };
  1638. /**
  1639. * Updates the Color3 rgb values from the given floats
  1640. * @param r defines the red component to read from
  1641. * @param g defines the green component to read from
  1642. * @param b defines the blue component to read from
  1643. * @returns the current Color3 object
  1644. */
  1645. Color3.prototype.copyFromFloats = function (r, g, b) {
  1646. this.r = r;
  1647. this.g = g;
  1648. this.b = b;
  1649. return this;
  1650. };
  1651. /**
  1652. * Updates the Color3 rgb values from the given floats
  1653. * @param r defines the red component to read from
  1654. * @param g defines the green component to read from
  1655. * @param b defines the blue component to read from
  1656. * @returns the current Color3 object
  1657. */
  1658. Color3.prototype.set = function (r, g, b) {
  1659. return this.copyFromFloats(r, g, b);
  1660. };
  1661. /**
  1662. * Compute the Color3 hexadecimal code as a string
  1663. * @returns a string containing the hexadecimal representation of the Color3 object
  1664. */
  1665. Color3.prototype.toHexString = function () {
  1666. var intR = (this.r * 255) | 0;
  1667. var intG = (this.g * 255) | 0;
  1668. var intB = (this.b * 255) | 0;
  1669. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1670. };
  1671. /**
  1672. * Computes a new Color3 converted from the current one to linear space
  1673. * @returns a new Color3 object
  1674. */
  1675. Color3.prototype.toLinearSpace = function () {
  1676. var convertedColor = new Color3();
  1677. this.toLinearSpaceToRef(convertedColor);
  1678. return convertedColor;
  1679. };
  1680. /**
  1681. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1682. * @param convertedColor defines the Color3 object where to store the linear space version
  1683. * @returns the unmodified Color3
  1684. */
  1685. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1686. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1687. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1688. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1689. return this;
  1690. };
  1691. /**
  1692. * Computes a new Color3 converted from the current one to gamma space
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.prototype.toGammaSpace = function () {
  1696. var convertedColor = new Color3();
  1697. this.toGammaSpaceToRef(convertedColor);
  1698. return convertedColor;
  1699. };
  1700. /**
  1701. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1702. * @param convertedColor defines the Color3 object where to store the gamma space version
  1703. * @returns the unmodified Color3
  1704. */
  1705. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1706. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1707. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1708. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1709. return this;
  1710. };
  1711. // Statics
  1712. /**
  1713. * Creates a new Color3 from the string containing valid hexadecimal values
  1714. * @param hex defines a string containing valid hexadecimal values
  1715. * @returns a new Color3 object
  1716. */
  1717. Color3.FromHexString = function (hex) {
  1718. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1719. return new Color3(0, 0, 0);
  1720. }
  1721. var r = parseInt(hex.substring(1, 3), 16);
  1722. var g = parseInt(hex.substring(3, 5), 16);
  1723. var b = parseInt(hex.substring(5, 7), 16);
  1724. return Color3.FromInts(r, g, b);
  1725. };
  1726. /**
  1727. * Creates a new Vector3 from the starting index of the given array
  1728. * @param array defines the source array
  1729. * @param offset defines an offset in the source array
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.FromArray = function (array, offset) {
  1733. if (offset === void 0) { offset = 0; }
  1734. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1735. };
  1736. /**
  1737. * Creates a new Color3 from integer values (< 256)
  1738. * @param r defines the red component to read from (value between 0 and 255)
  1739. * @param g defines the green component to read from (value between 0 and 255)
  1740. * @param b defines the blue component to read from (value between 0 and 255)
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromInts = function (r, g, b) {
  1744. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1745. };
  1746. /**
  1747. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1748. * @param start defines the start Color3 value
  1749. * @param end defines the end Color3 value
  1750. * @param amount defines the gradient value between start and end
  1751. * @returns a new Color3 object
  1752. */
  1753. Color3.Lerp = function (start, end, amount) {
  1754. var r = start.r + ((end.r - start.r) * amount);
  1755. var g = start.g + ((end.g - start.g) * amount);
  1756. var b = start.b + ((end.b - start.b) * amount);
  1757. return new Color3(r, g, b);
  1758. };
  1759. /**
  1760. * Returns a Color3 value containing a red color
  1761. * @returns a new Color3 object
  1762. */
  1763. Color3.Red = function () { return new Color3(1, 0, 0); };
  1764. /**
  1765. * Returns a Color3 value containing a green color
  1766. * @returns a new Color3 object
  1767. */
  1768. Color3.Green = function () { return new Color3(0, 1, 0); };
  1769. /**
  1770. * Returns a Color3 value containing a blue color
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1774. /**
  1775. * Returns a Color3 value containing a black color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Black = function () { return new Color3(0, 0, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a white color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.White = function () { return new Color3(1, 1, 1); };
  1784. /**
  1785. * Returns a Color3 value containing a purple color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1789. /**
  1790. * Returns a Color3 value containing a magenta color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1794. /**
  1795. * Returns a Color3 value containing a yellow color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1799. /**
  1800. * Returns a Color3 value containing a gray color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1804. /**
  1805. * Returns a Color3 value containing a teal color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1809. /**
  1810. * Returns a Color3 value containing a random color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1814. return Color3;
  1815. }());
  1816. BABYLON.Color3 = Color3;
  1817. /**
  1818. * Class used to hold a RBGA color
  1819. */
  1820. var Color4 = /** @class */ (function () {
  1821. /**
  1822. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1823. * @param r defines the red component (between 0 and 1, default is 0)
  1824. * @param g defines the green component (between 0 and 1, default is 0)
  1825. * @param b defines the blue component (between 0 and 1, default is 0)
  1826. * @param a defines the alpha component (between 0 and 1, default is 1)
  1827. */
  1828. function Color4(
  1829. /**
  1830. * Defines the red component (between 0 and 1, default is 0)
  1831. */
  1832. r,
  1833. /**
  1834. * Defines the green component (between 0 and 1, default is 0)
  1835. */
  1836. g,
  1837. /**
  1838. * Defines the blue component (between 0 and 1, default is 0)
  1839. */
  1840. b,
  1841. /**
  1842. * Defines the alpha component (between 0 and 1, default is 1)
  1843. */
  1844. a) {
  1845. if (r === void 0) { r = 0; }
  1846. if (g === void 0) { g = 0; }
  1847. if (b === void 0) { b = 0; }
  1848. if (a === void 0) { a = 1; }
  1849. this.r = r;
  1850. this.g = g;
  1851. this.b = b;
  1852. this.a = a;
  1853. }
  1854. // Operators
  1855. /**
  1856. * Adds in place the given Color4 values to the current Color4 object
  1857. * @param right defines the second operand
  1858. * @returns the current updated Color4 object
  1859. */
  1860. Color4.prototype.addInPlace = function (right) {
  1861. this.r += right.r;
  1862. this.g += right.g;
  1863. this.b += right.b;
  1864. this.a += right.a;
  1865. return this;
  1866. };
  1867. /**
  1868. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1869. * @returns the new array
  1870. */
  1871. Color4.prototype.asArray = function () {
  1872. var result = new Array();
  1873. this.toArray(result, 0);
  1874. return result;
  1875. };
  1876. /**
  1877. * Stores from the starting index in the given array the Color4 successive values
  1878. * @param array defines the array where to store the r,g,b components
  1879. * @param index defines an optional index in the target array to define where to start storing values
  1880. * @returns the current Color4 object
  1881. */
  1882. Color4.prototype.toArray = function (array, index) {
  1883. if (index === undefined) {
  1884. index = 0;
  1885. }
  1886. array[index] = this.r;
  1887. array[index + 1] = this.g;
  1888. array[index + 2] = this.b;
  1889. array[index + 3] = this.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1894. * @param right defines the second operand
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.add = function (right) {
  1898. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1899. };
  1900. /**
  1901. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1902. * @param right defines the second operand
  1903. * @returns a new Color4 object
  1904. */
  1905. Color4.prototype.subtract = function (right) {
  1906. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1907. };
  1908. /**
  1909. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1910. * @param right defines the second operand
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the current Color4 object
  1913. */
  1914. Color4.prototype.subtractToRef = function (right, result) {
  1915. result.r = this.r - right.r;
  1916. result.g = this.g - right.g;
  1917. result.b = this.b - right.b;
  1918. result.a = this.a - right.a;
  1919. return this;
  1920. };
  1921. /**
  1922. * Creates a new Color4 with the current Color4 values multiplied by scale
  1923. * @param scale defines the scaling factor to apply
  1924. * @returns a new Color4 object
  1925. */
  1926. Color4.prototype.scale = function (scale) {
  1927. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1928. };
  1929. /**
  1930. * Multiplies the current Color4 values by scale and stores the result in "result"
  1931. * @param scale defines the scaling factor to apply
  1932. * @param result defines the Color4 object where to store the result
  1933. * @returns the current unmodified Color4
  1934. */
  1935. Color4.prototype.scaleToRef = function (scale, result) {
  1936. result.r = this.r * scale;
  1937. result.g = this.g * scale;
  1938. result.b = this.b * scale;
  1939. result.a = this.a * scale;
  1940. return this;
  1941. };
  1942. /**
  1943. * Scale the current Color4 values by a factor and add the result to a given Color4
  1944. * @param scale defines the scale factor
  1945. * @param result defines the Color4 object where to store the result
  1946. * @returns the unmodified current Color4
  1947. */
  1948. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1949. result.r += this.r * scale;
  1950. result.g += this.g * scale;
  1951. result.b += this.b * scale;
  1952. result.a += this.a * scale;
  1953. return this;
  1954. };
  1955. /**
  1956. * Clamps the rgb values by the min and max values and stores the result into "result"
  1957. * @param min defines minimum clamping value (default is 0)
  1958. * @param max defines maximum clamping value (default is 1)
  1959. * @param result defines color to store the result into.
  1960. * @returns the cuurent Color4
  1961. */
  1962. Color4.prototype.clampToRef = function (min, max, result) {
  1963. if (min === void 0) { min = 0; }
  1964. if (max === void 0) { max = 1; }
  1965. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1966. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1967. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1968. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1969. return this;
  1970. };
  1971. /**
  1972. * Multipy an Color4 value by another and return a new Color4 object
  1973. * @param color defines the Color4 value to multiply by
  1974. * @returns a new Color4 object
  1975. */
  1976. Color4.prototype.multiply = function (color) {
  1977. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1978. };
  1979. /**
  1980. * Multipy a Color4 value by another and push the result in a reference value
  1981. * @param color defines the Color4 value to multiply by
  1982. * @param result defines the Color4 to fill the result in
  1983. * @returns the result Color4
  1984. */
  1985. Color4.prototype.multiplyToRef = function (color, result) {
  1986. result.r = this.r * color.r;
  1987. result.g = this.g * color.g;
  1988. result.b = this.b * color.b;
  1989. result.a = this.a * color.a;
  1990. return result;
  1991. };
  1992. /**
  1993. * Creates a string with the Color4 current values
  1994. * @returns the string representation of the Color4 object
  1995. */
  1996. Color4.prototype.toString = function () {
  1997. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1998. };
  1999. /**
  2000. * Returns the string "Color4"
  2001. * @returns "Color4"
  2002. */
  2003. Color4.prototype.getClassName = function () {
  2004. return "Color4";
  2005. };
  2006. /**
  2007. * Compute the Color4 hash code
  2008. * @returns an unique number that can be used to hash Color4 objects
  2009. */
  2010. Color4.prototype.getHashCode = function () {
  2011. var hash = this.r || 0;
  2012. hash = (hash * 397) ^ (this.g || 0);
  2013. hash = (hash * 397) ^ (this.b || 0);
  2014. hash = (hash * 397) ^ (this.a || 0);
  2015. return hash;
  2016. };
  2017. /**
  2018. * Creates a new Color4 copied from the current one
  2019. * @returns a new Color4 object
  2020. */
  2021. Color4.prototype.clone = function () {
  2022. return new Color4(this.r, this.g, this.b, this.a);
  2023. };
  2024. /**
  2025. * Copies the given Color4 values into the current one
  2026. * @param source defines the source Color4 object
  2027. * @returns the current updated Color4 object
  2028. */
  2029. Color4.prototype.copyFrom = function (source) {
  2030. this.r = source.r;
  2031. this.g = source.g;
  2032. this.b = source.b;
  2033. this.a = source.a;
  2034. return this;
  2035. };
  2036. /**
  2037. * Copies the given float values into the current one
  2038. * @param r defines the red component to read from
  2039. * @param g defines the green component to read from
  2040. * @param b defines the blue component to read from
  2041. * @param a defines the alpha component to read from
  2042. * @returns the current updated Color4 object
  2043. */
  2044. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2045. this.r = r;
  2046. this.g = g;
  2047. this.b = b;
  2048. this.a = a;
  2049. return this;
  2050. };
  2051. /**
  2052. * Copies the given float values into the current one
  2053. * @param r defines the red component to read from
  2054. * @param g defines the green component to read from
  2055. * @param b defines the blue component to read from
  2056. * @param a defines the alpha component to read from
  2057. * @returns the current updated Color4 object
  2058. */
  2059. Color4.prototype.set = function (r, g, b, a) {
  2060. return this.copyFromFloats(r, g, b, a);
  2061. };
  2062. /**
  2063. * Compute the Color4 hexadecimal code as a string
  2064. * @returns a string containing the hexadecimal representation of the Color4 object
  2065. */
  2066. Color4.prototype.toHexString = function () {
  2067. var intR = (this.r * 255) | 0;
  2068. var intG = (this.g * 255) | 0;
  2069. var intB = (this.b * 255) | 0;
  2070. var intA = (this.a * 255) | 0;
  2071. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2072. };
  2073. /**
  2074. * Computes a new Color4 converted from the current one to linear space
  2075. * @returns a new Color4 object
  2076. */
  2077. Color4.prototype.toLinearSpace = function () {
  2078. var convertedColor = new Color4();
  2079. this.toLinearSpaceToRef(convertedColor);
  2080. return convertedColor;
  2081. };
  2082. /**
  2083. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2084. * @param convertedColor defines the Color4 object where to store the linear space version
  2085. * @returns the unmodified Color4
  2086. */
  2087. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2088. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2089. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2090. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2091. convertedColor.a = this.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Computes a new Color4 converted from the current one to gamma space
  2096. * @returns a new Color4 object
  2097. */
  2098. Color4.prototype.toGammaSpace = function () {
  2099. var convertedColor = new Color4();
  2100. this.toGammaSpaceToRef(convertedColor);
  2101. return convertedColor;
  2102. };
  2103. /**
  2104. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2105. * @param convertedColor defines the Color4 object where to store the gamma space version
  2106. * @returns the unmodified Color4
  2107. */
  2108. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2109. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2110. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2111. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2112. convertedColor.a = this.a;
  2113. return this;
  2114. };
  2115. // Statics
  2116. /**
  2117. * Creates a new Color4 from the string containing valid hexadecimal values
  2118. * @param hex defines a string containing valid hexadecimal values
  2119. * @returns a new Color4 object
  2120. */
  2121. Color4.FromHexString = function (hex) {
  2122. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2123. return new Color4(0.0, 0.0, 0.0, 0.0);
  2124. }
  2125. var r = parseInt(hex.substring(1, 3), 16);
  2126. var g = parseInt(hex.substring(3, 5), 16);
  2127. var b = parseInt(hex.substring(5, 7), 16);
  2128. var a = parseInt(hex.substring(7, 9), 16);
  2129. return Color4.FromInts(r, g, b, a);
  2130. };
  2131. /**
  2132. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2133. * @param left defines the start value
  2134. * @param right defines the end value
  2135. * @param amount defines the gradient factor
  2136. * @returns a new Color4 object
  2137. */
  2138. Color4.Lerp = function (left, right, amount) {
  2139. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2140. Color4.LerpToRef(left, right, amount, result);
  2141. return result;
  2142. };
  2143. /**
  2144. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2145. * @param left defines the start value
  2146. * @param right defines the end value
  2147. * @param amount defines the gradient factor
  2148. * @param result defines the Color4 object where to store data
  2149. */
  2150. Color4.LerpToRef = function (left, right, amount, result) {
  2151. result.r = left.r + (right.r - left.r) * amount;
  2152. result.g = left.g + (right.g - left.g) * amount;
  2153. result.b = left.b + (right.b - left.b) * amount;
  2154. result.a = left.a + (right.a - left.a) * amount;
  2155. };
  2156. /**
  2157. * Creates a new Color4 from the starting index element of the given array
  2158. * @param array defines the source array to read from
  2159. * @param offset defines the offset in the source array
  2160. * @returns a new Color4 object
  2161. */
  2162. Color4.FromArray = function (array, offset) {
  2163. if (offset === void 0) { offset = 0; }
  2164. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2165. };
  2166. /**
  2167. * Creates a new Color3 from integer values (< 256)
  2168. * @param r defines the red component to read from (value between 0 and 255)
  2169. * @param g defines the green component to read from (value between 0 and 255)
  2170. * @param b defines the blue component to read from (value between 0 and 255)
  2171. * @param a defines the alpha component to read from (value between 0 and 255)
  2172. * @returns a new Color3 object
  2173. */
  2174. Color4.FromInts = function (r, g, b, a) {
  2175. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2176. };
  2177. /**
  2178. * Check the content of a given array and convert it to an array containing RGBA data
  2179. * If the original array was already containing count * 4 values then it is returned directly
  2180. * @param colors defines the array to check
  2181. * @param count defines the number of RGBA data to expect
  2182. * @returns an array containing count * 4 values (RGBA)
  2183. */
  2184. Color4.CheckColors4 = function (colors, count) {
  2185. // Check if color3 was used
  2186. if (colors.length === count * 3) {
  2187. var colors4 = [];
  2188. for (var index = 0; index < colors.length; index += 3) {
  2189. var newIndex = (index / 3) * 4;
  2190. colors4[newIndex] = colors[index];
  2191. colors4[newIndex + 1] = colors[index + 1];
  2192. colors4[newIndex + 2] = colors[index + 2];
  2193. colors4[newIndex + 3] = 1.0;
  2194. }
  2195. return colors4;
  2196. }
  2197. return colors;
  2198. };
  2199. return Color4;
  2200. }());
  2201. BABYLON.Color4 = Color4;
  2202. /**
  2203. * Class representing a vector containing 2 coordinates
  2204. */
  2205. var Vector2 = /** @class */ (function () {
  2206. /**
  2207. * Creates a new Vector2 from the given x and y coordinates
  2208. * @param x defines the first coordinate
  2209. * @param y defines the second coordinate
  2210. */
  2211. function Vector2(
  2212. /** defines the first coordinate */
  2213. x,
  2214. /** defines the second coordinate */
  2215. y) {
  2216. if (x === void 0) { x = 0; }
  2217. if (y === void 0) { y = 0; }
  2218. this.x = x;
  2219. this.y = y;
  2220. }
  2221. /**
  2222. * Gets a string with the Vector2 coordinates
  2223. * @returns a string with the Vector2 coordinates
  2224. */
  2225. Vector2.prototype.toString = function () {
  2226. return "{X: " + this.x + " Y:" + this.y + "}";
  2227. };
  2228. /**
  2229. * Gets class name
  2230. * @returns the string "Vector2"
  2231. */
  2232. Vector2.prototype.getClassName = function () {
  2233. return "Vector2";
  2234. };
  2235. /**
  2236. * Gets current vector hash code
  2237. * @returns the Vector2 hash code as a number
  2238. */
  2239. Vector2.prototype.getHashCode = function () {
  2240. var hash = this.x || 0;
  2241. hash = (hash * 397) ^ (this.y || 0);
  2242. return hash;
  2243. };
  2244. // Operators
  2245. /**
  2246. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2247. * @param array defines the source array
  2248. * @param index defines the offset in source array
  2249. * @returns the current Vector2
  2250. */
  2251. Vector2.prototype.toArray = function (array, index) {
  2252. if (index === void 0) { index = 0; }
  2253. array[index] = this.x;
  2254. array[index + 1] = this.y;
  2255. return this;
  2256. };
  2257. /**
  2258. * Copy the current vector to an array
  2259. * @returns a new array with 2 elements: the Vector2 coordinates.
  2260. */
  2261. Vector2.prototype.asArray = function () {
  2262. var result = new Array();
  2263. this.toArray(result, 0);
  2264. return result;
  2265. };
  2266. /**
  2267. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2268. * @param source defines the source Vector2
  2269. * @returns the current updated Vector2
  2270. */
  2271. Vector2.prototype.copyFrom = function (source) {
  2272. this.x = source.x;
  2273. this.y = source.y;
  2274. return this;
  2275. };
  2276. /**
  2277. * Sets the Vector2 coordinates with the given floats
  2278. * @param x defines the first coordinate
  2279. * @param y defines the second coordinate
  2280. * @returns the current updated Vector2
  2281. */
  2282. Vector2.prototype.copyFromFloats = function (x, y) {
  2283. this.x = x;
  2284. this.y = y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Sets the Vector2 coordinates with the given floats
  2289. * @param x defines the first coordinate
  2290. * @param y defines the second coordinate
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.set = function (x, y) {
  2294. return this.copyFromFloats(x, y);
  2295. };
  2296. /**
  2297. * Add another vector with the current one
  2298. * @param otherVector defines the other vector
  2299. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2300. */
  2301. Vector2.prototype.add = function (otherVector) {
  2302. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2303. };
  2304. /**
  2305. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2306. * @param otherVector defines the other vector
  2307. * @param result defines the target vector
  2308. * @returns the unmodified current Vector2
  2309. */
  2310. Vector2.prototype.addToRef = function (otherVector, result) {
  2311. result.x = this.x + otherVector.x;
  2312. result.y = this.y + otherVector.y;
  2313. return this;
  2314. };
  2315. /**
  2316. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2317. * @param otherVector defines the other vector
  2318. * @returns the current updated Vector2
  2319. */
  2320. Vector2.prototype.addInPlace = function (otherVector) {
  2321. this.x += otherVector.x;
  2322. this.y += otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns a new Vector2
  2329. */
  2330. Vector2.prototype.addVector3 = function (otherVector) {
  2331. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2332. };
  2333. /**
  2334. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2335. * @param otherVector defines the other vector
  2336. * @returns a new Vector2
  2337. */
  2338. Vector2.prototype.subtract = function (otherVector) {
  2339. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2340. };
  2341. /**
  2342. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2343. * @param otherVector defines the other vector
  2344. * @param result defines the target vector
  2345. * @returns the unmodified current Vector2
  2346. */
  2347. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2348. result.x = this.x - otherVector.x;
  2349. result.y = this.y - otherVector.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2354. * @param otherVector defines the other vector
  2355. * @returns the current updated Vector2
  2356. */
  2357. Vector2.prototype.subtractInPlace = function (otherVector) {
  2358. this.x -= otherVector.x;
  2359. this.y -= otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Multiplies in place the current Vector2 coordinates by the given ones
  2364. * @param otherVector defines the other vector
  2365. * @returns the current updated Vector2
  2366. */
  2367. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2368. this.x *= otherVector.x;
  2369. this.y *= otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @returns a new Vector2
  2376. */
  2377. Vector2.prototype.multiply = function (otherVector) {
  2378. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2379. };
  2380. /**
  2381. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2382. * @param otherVector defines the other vector
  2383. * @param result defines the target vector
  2384. * @returns the unmodified current Vector2
  2385. */
  2386. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2387. result.x = this.x * otherVector.x;
  2388. result.y = this.y * otherVector.y;
  2389. return this;
  2390. };
  2391. /**
  2392. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2393. * @param x defines the first coordinate
  2394. * @param y defines the second coordinate
  2395. * @returns a new Vector2
  2396. */
  2397. Vector2.prototype.multiplyByFloats = function (x, y) {
  2398. return new Vector2(this.x * x, this.y * y);
  2399. };
  2400. /**
  2401. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2402. * @param otherVector defines the other vector
  2403. * @returns a new Vector2
  2404. */
  2405. Vector2.prototype.divide = function (otherVector) {
  2406. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2407. };
  2408. /**
  2409. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2410. * @param otherVector defines the other vector
  2411. * @param result defines the target vector
  2412. * @returns the unmodified current Vector2
  2413. */
  2414. Vector2.prototype.divideToRef = function (otherVector, result) {
  2415. result.x = this.x / otherVector.x;
  2416. result.y = this.y / otherVector.y;
  2417. return this;
  2418. };
  2419. /**
  2420. * Divides the current Vector3 coordinates by the given ones
  2421. * @param otherVector defines the other vector
  2422. * @returns the current updated Vector2
  2423. */
  2424. Vector2.prototype.divideInPlace = function (otherVector) {
  2425. return this.divideToRef(otherVector, this);
  2426. };
  2427. /**
  2428. * Gets a new Vector2 with current Vector2 negated coordinates
  2429. * @returns a new Vector2
  2430. */
  2431. Vector2.prototype.negate = function () {
  2432. return new Vector2(-this.x, -this.y);
  2433. };
  2434. /**
  2435. * Multiply the Vector2 coordinates by scale
  2436. * @param scale defines the scaling factor
  2437. * @returns the current updated Vector2
  2438. */
  2439. Vector2.prototype.scaleInPlace = function (scale) {
  2440. this.x *= scale;
  2441. this.y *= scale;
  2442. return this;
  2443. };
  2444. /**
  2445. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2446. * @param scale defines the scaling factor
  2447. * @returns a new Vector2
  2448. */
  2449. Vector2.prototype.scale = function (scale) {
  2450. var result = new Vector2(0, 0);
  2451. this.scaleToRef(scale, result);
  2452. return result;
  2453. };
  2454. /**
  2455. * Scale the current Vector2 values by a factor to a given Vector2
  2456. * @param scale defines the scale factor
  2457. * @param result defines the Vector2 object where to store the result
  2458. * @returns the unmodified current Vector2
  2459. */
  2460. Vector2.prototype.scaleToRef = function (scale, result) {
  2461. result.x = this.x * scale;
  2462. result.y = this.y * scale;
  2463. return this;
  2464. };
  2465. /**
  2466. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2467. * @param scale defines the scale factor
  2468. * @param result defines the Vector2 object where to store the result
  2469. * @returns the unmodified current Vector2
  2470. */
  2471. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2472. result.x += this.x * scale;
  2473. result.y += this.y * scale;
  2474. return this;
  2475. };
  2476. /**
  2477. * Gets a boolean if two vectors are equals
  2478. * @param otherVector defines the other vector
  2479. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2480. */
  2481. Vector2.prototype.equals = function (otherVector) {
  2482. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2483. };
  2484. /**
  2485. * Gets a boolean if two vectors are equals (using an epsilon value)
  2486. * @param otherVector defines the other vector
  2487. * @param epsilon defines the minimal distance to consider equality
  2488. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2489. */
  2490. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2491. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2492. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2493. };
  2494. // Properties
  2495. /**
  2496. * Gets the length of the vector
  2497. * @returns the vector length (float)
  2498. */
  2499. Vector2.prototype.length = function () {
  2500. return Math.sqrt(this.x * this.x + this.y * this.y);
  2501. };
  2502. /**
  2503. * Gets the vector squared length
  2504. * @returns the vector squared length (float)
  2505. */
  2506. Vector2.prototype.lengthSquared = function () {
  2507. return (this.x * this.x + this.y * this.y);
  2508. };
  2509. // Methods
  2510. /**
  2511. * Normalize the vector
  2512. * @returns the current updated Vector2
  2513. */
  2514. Vector2.prototype.normalize = function () {
  2515. var len = this.length();
  2516. if (len === 0)
  2517. return this;
  2518. var num = 1.0 / len;
  2519. this.x *= num;
  2520. this.y *= num;
  2521. return this;
  2522. };
  2523. /**
  2524. * Gets a new Vector2 copied from the Vector2
  2525. * @returns a new Vector2
  2526. */
  2527. Vector2.prototype.clone = function () {
  2528. return new Vector2(this.x, this.y);
  2529. };
  2530. // Statics
  2531. /**
  2532. * Gets a new Vector2(0, 0)
  2533. * @returns a new Vector2
  2534. */
  2535. Vector2.Zero = function () {
  2536. return new Vector2(0, 0);
  2537. };
  2538. /**
  2539. * Gets a new Vector2(1, 1)
  2540. * @returns a new Vector2
  2541. */
  2542. Vector2.One = function () {
  2543. return new Vector2(1, 1);
  2544. };
  2545. /**
  2546. * Gets a new Vector2 set from the given index element of the given array
  2547. * @param array defines the data source
  2548. * @param offset defines the offset in the data source
  2549. * @returns a new Vector2
  2550. */
  2551. Vector2.FromArray = function (array, offset) {
  2552. if (offset === void 0) { offset = 0; }
  2553. return new Vector2(array[offset], array[offset + 1]);
  2554. };
  2555. /**
  2556. * Sets "result" from the given index element of the given array
  2557. * @param array defines the data source
  2558. * @param offset defines the offset in the data source
  2559. * @param result defines the target vector
  2560. */
  2561. Vector2.FromArrayToRef = function (array, offset, result) {
  2562. result.x = array[offset];
  2563. result.y = array[offset + 1];
  2564. };
  2565. /**
  2566. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2567. * @param value1 defines 1st point of control
  2568. * @param value2 defines 2nd point of control
  2569. * @param value3 defines 3rd point of control
  2570. * @param value4 defines 4th point of control
  2571. * @param amount defines the interpolation factor
  2572. * @returns a new Vector2
  2573. */
  2574. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2575. var squared = amount * amount;
  2576. var cubed = amount * squared;
  2577. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2578. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2579. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2580. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2581. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2582. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2583. return new Vector2(x, y);
  2584. };
  2585. /**
  2586. * 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".
  2587. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2588. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2589. * @param value defines the value to clamp
  2590. * @param min defines the lower limit
  2591. * @param max defines the upper limit
  2592. * @returns a new Vector2
  2593. */
  2594. Vector2.Clamp = function (value, min, max) {
  2595. var x = value.x;
  2596. x = (x > max.x) ? max.x : x;
  2597. x = (x < min.x) ? min.x : x;
  2598. var y = value.y;
  2599. y = (y > max.y) ? max.y : y;
  2600. y = (y < min.y) ? min.y : y;
  2601. return new Vector2(x, y);
  2602. };
  2603. /**
  2604. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2605. * @param value1 defines the 1st control point
  2606. * @param tangent1 defines the outgoing tangent
  2607. * @param value2 defines the 2nd control point
  2608. * @param tangent2 defines the incoming tangent
  2609. * @param amount defines the interpolation factor
  2610. * @returns a new Vector2
  2611. */
  2612. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2613. var squared = amount * amount;
  2614. var cubed = amount * squared;
  2615. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2616. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2617. var part3 = (cubed - (2.0 * squared)) + amount;
  2618. var part4 = cubed - squared;
  2619. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2620. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2621. return new Vector2(x, y);
  2622. };
  2623. /**
  2624. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2625. * @param start defines the start vector
  2626. * @param end defines the end vector
  2627. * @param amount defines the interpolation factor
  2628. * @returns a new Vector2
  2629. */
  2630. Vector2.Lerp = function (start, end, amount) {
  2631. var x = start.x + ((end.x - start.x) * amount);
  2632. var y = start.y + ((end.y - start.y) * amount);
  2633. return new Vector2(x, y);
  2634. };
  2635. /**
  2636. * Gets the dot product of the vector "left" and the vector "right"
  2637. * @param left defines first vector
  2638. * @param right defines second vector
  2639. * @returns the dot product (float)
  2640. */
  2641. Vector2.Dot = function (left, right) {
  2642. return left.x * right.x + left.y * right.y;
  2643. };
  2644. /**
  2645. * Returns a new Vector2 equal to the normalized given vector
  2646. * @param vector defines the vector to normalize
  2647. * @returns a new Vector2
  2648. */
  2649. Vector2.Normalize = function (vector) {
  2650. var newVector = vector.clone();
  2651. newVector.normalize();
  2652. return newVector;
  2653. };
  2654. /**
  2655. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2656. * @param left defines 1st vector
  2657. * @param right defines 2nd vector
  2658. * @returns a new Vector2
  2659. */
  2660. Vector2.Minimize = function (left, right) {
  2661. var x = (left.x < right.x) ? left.x : right.x;
  2662. var y = (left.y < right.y) ? left.y : right.y;
  2663. return new Vector2(x, y);
  2664. };
  2665. /**
  2666. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2667. * @param left defines 1st vector
  2668. * @param right defines 2nd vector
  2669. * @returns a new Vector2
  2670. */
  2671. Vector2.Maximize = function (left, right) {
  2672. var x = (left.x > right.x) ? left.x : right.x;
  2673. var y = (left.y > right.y) ? left.y : right.y;
  2674. return new Vector2(x, y);
  2675. };
  2676. /**
  2677. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2678. * @param vector defines the vector to transform
  2679. * @param transformation defines the matrix to apply
  2680. * @returns a new Vector2
  2681. */
  2682. Vector2.Transform = function (vector, transformation) {
  2683. var r = Vector2.Zero();
  2684. Vector2.TransformToRef(vector, transformation, r);
  2685. return r;
  2686. };
  2687. /**
  2688. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2689. * @param vector defines the vector to transform
  2690. * @param transformation defines the matrix to apply
  2691. * @param result defines the target vector
  2692. */
  2693. Vector2.TransformToRef = function (vector, transformation, result) {
  2694. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2695. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2696. result.x = x;
  2697. result.y = y;
  2698. };
  2699. /**
  2700. * Determines if a given vector is included in a triangle
  2701. * @param p defines the vector to test
  2702. * @param p0 defines 1st triangle point
  2703. * @param p1 defines 2nd triangle point
  2704. * @param p2 defines 3rd triangle point
  2705. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2706. */
  2707. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2708. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2709. var sign = a < 0 ? -1 : 1;
  2710. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2711. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2712. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2713. };
  2714. /**
  2715. * Gets the distance between the vectors "value1" and "value2"
  2716. * @param value1 defines first vector
  2717. * @param value2 defines second vector
  2718. * @returns the distance between vectors
  2719. */
  2720. Vector2.Distance = function (value1, value2) {
  2721. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2722. };
  2723. /**
  2724. * Returns the squared distance between the vectors "value1" and "value2"
  2725. * @param value1 defines first vector
  2726. * @param value2 defines second vector
  2727. * @returns the squared distance between vectors
  2728. */
  2729. Vector2.DistanceSquared = function (value1, value2) {
  2730. var x = value1.x - value2.x;
  2731. var y = value1.y - value2.y;
  2732. return (x * x) + (y * y);
  2733. };
  2734. /**
  2735. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2736. * @param value1 defines first vector
  2737. * @param value2 defines second vector
  2738. * @returns a new Vector2
  2739. */
  2740. Vector2.Center = function (value1, value2) {
  2741. var center = value1.add(value2);
  2742. center.scaleInPlace(0.5);
  2743. return center;
  2744. };
  2745. /**
  2746. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2747. * @param p defines the middle point
  2748. * @param segA defines one point of the segment
  2749. * @param segB defines the other point of the segment
  2750. * @returns the shortest distance
  2751. */
  2752. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2753. var l2 = Vector2.DistanceSquared(segA, segB);
  2754. if (l2 === 0.0) {
  2755. return Vector2.Distance(p, segA);
  2756. }
  2757. var v = segB.subtract(segA);
  2758. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2759. var proj = segA.add(v.multiplyByFloats(t, t));
  2760. return Vector2.Distance(p, proj);
  2761. };
  2762. return Vector2;
  2763. }());
  2764. BABYLON.Vector2 = Vector2;
  2765. /**
  2766. * Classed used to store (x,y,z) vector representation
  2767. * A Vector3 is the main object used in 3D geometry
  2768. * It can represent etiher the coordinates of a point the space, either a direction
  2769. * Reminder: Babylon.js uses a left handed forward facing system
  2770. */
  2771. var Vector3 = /** @class */ (function () {
  2772. /**
  2773. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2774. * @param x defines the first coordinates (on X axis)
  2775. * @param y defines the second coordinates (on Y axis)
  2776. * @param z defines the third coordinates (on Z axis)
  2777. */
  2778. function Vector3(
  2779. /**
  2780. * Defines the first coordinates (on X axis)
  2781. */
  2782. x,
  2783. /**
  2784. * Defines the second coordinates (on Y axis)
  2785. */
  2786. y,
  2787. /**
  2788. * Defines the third coordinates (on Z axis)
  2789. */
  2790. z) {
  2791. if (x === void 0) { x = 0; }
  2792. if (y === void 0) { y = 0; }
  2793. if (z === void 0) { z = 0; }
  2794. this.x = x;
  2795. this.y = y;
  2796. this.z = z;
  2797. }
  2798. /**
  2799. * Creates a string representation of the Vector3
  2800. * @returns a string with the Vector3 coordinates.
  2801. */
  2802. Vector3.prototype.toString = function () {
  2803. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2804. };
  2805. /**
  2806. * Gets the class name
  2807. * @returns the string "Vector3"
  2808. */
  2809. Vector3.prototype.getClassName = function () {
  2810. return "Vector3";
  2811. };
  2812. /**
  2813. * Creates the Vector3 hash code
  2814. * @returns a number which tends to be unique between Vector3 instances
  2815. */
  2816. Vector3.prototype.getHashCode = function () {
  2817. var hash = this.x || 0;
  2818. hash = (hash * 397) ^ (this.y || 0);
  2819. hash = (hash * 397) ^ (this.z || 0);
  2820. return hash;
  2821. };
  2822. // Operators
  2823. /**
  2824. * Creates an array containing three elements : the coordinates of the Vector3
  2825. * @returns a new array of numbers
  2826. */
  2827. Vector3.prototype.asArray = function () {
  2828. var result = [];
  2829. this.toArray(result, 0);
  2830. return result;
  2831. };
  2832. /**
  2833. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2834. * @param array defines the destination array
  2835. * @param index defines the offset in the destination array
  2836. * @returns the current Vector3
  2837. */
  2838. Vector3.prototype.toArray = function (array, index) {
  2839. if (index === void 0) { index = 0; }
  2840. array[index] = this.x;
  2841. array[index + 1] = this.y;
  2842. array[index + 2] = this.z;
  2843. return this;
  2844. };
  2845. /**
  2846. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2847. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2848. */
  2849. Vector3.prototype.toQuaternion = function () {
  2850. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2851. };
  2852. /**
  2853. * Adds the given vector to the current Vector3
  2854. * @param otherVector defines the second operand
  2855. * @returns the current updated Vector3
  2856. */
  2857. Vector3.prototype.addInPlace = function (otherVector) {
  2858. this.x += otherVector.x;
  2859. this.y += otherVector.y;
  2860. this.z += otherVector.z;
  2861. return this;
  2862. };
  2863. /**
  2864. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2865. * @param otherVector defines the second operand
  2866. * @returns the resulting Vector3
  2867. */
  2868. Vector3.prototype.add = function (otherVector) {
  2869. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2870. };
  2871. /**
  2872. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2873. * @param otherVector defines the second operand
  2874. * @param result defines the Vector3 object where to store the result
  2875. * @returns the current Vector3
  2876. */
  2877. Vector3.prototype.addToRef = function (otherVector, result) {
  2878. result.x = this.x + otherVector.x;
  2879. result.y = this.y + otherVector.y;
  2880. result.z = this.z + otherVector.z;
  2881. return this;
  2882. };
  2883. /**
  2884. * Subtract the given vector from the current Vector3
  2885. * @param otherVector defines the second operand
  2886. * @returns the current updated Vector3
  2887. */
  2888. Vector3.prototype.subtractInPlace = function (otherVector) {
  2889. this.x -= otherVector.x;
  2890. this.y -= otherVector.y;
  2891. this.z -= otherVector.z;
  2892. return this;
  2893. };
  2894. /**
  2895. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2896. * @param otherVector defines the second operand
  2897. * @returns the resulting Vector3
  2898. */
  2899. Vector3.prototype.subtract = function (otherVector) {
  2900. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2901. };
  2902. /**
  2903. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2904. * @param otherVector defines the second operand
  2905. * @param result defines the Vector3 object where to store the result
  2906. * @returns the current Vector3
  2907. */
  2908. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2909. result.x = this.x - otherVector.x;
  2910. result.y = this.y - otherVector.y;
  2911. result.z = this.z - otherVector.z;
  2912. return this;
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2916. * @param x defines the x coordinate of the operand
  2917. * @param y defines the y coordinate of the operand
  2918. * @param z defines the z coordinate of the operand
  2919. * @returns the resulting Vector3
  2920. */
  2921. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2922. return new Vector3(this.x - x, this.y - y, this.z - z);
  2923. };
  2924. /**
  2925. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2926. * @param x defines the x coordinate of the operand
  2927. * @param y defines the y coordinate of the operand
  2928. * @param z defines the z coordinate of the operand
  2929. * @param result defines the Vector3 object where to store the result
  2930. * @returns the current Vector3
  2931. */
  2932. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2933. result.x = this.x - x;
  2934. result.y = this.y - y;
  2935. result.z = this.z - z;
  2936. return this;
  2937. };
  2938. /**
  2939. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2940. * @returns a new Vector3
  2941. */
  2942. Vector3.prototype.negate = function () {
  2943. return new Vector3(-this.x, -this.y, -this.z);
  2944. };
  2945. /**
  2946. * Multiplies the Vector3 coordinates by the float "scale"
  2947. * @param scale defines the multiplier factor
  2948. * @returns the current updated Vector3
  2949. */
  2950. Vector3.prototype.scaleInPlace = function (scale) {
  2951. this.x *= scale;
  2952. this.y *= scale;
  2953. this.z *= scale;
  2954. return this;
  2955. };
  2956. /**
  2957. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2958. * @param scale defines the multiplier factor
  2959. * @returns a new Vector3
  2960. */
  2961. Vector3.prototype.scale = function (scale) {
  2962. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2963. };
  2964. /**
  2965. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2966. * @param scale defines the multiplier factor
  2967. * @param result defines the Vector3 object where to store the result
  2968. * @returns the current Vector3
  2969. */
  2970. Vector3.prototype.scaleToRef = function (scale, result) {
  2971. result.x = this.x * scale;
  2972. result.y = this.y * scale;
  2973. result.z = this.z * scale;
  2974. return this;
  2975. };
  2976. /**
  2977. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2978. * @param scale defines the scale factor
  2979. * @param result defines the Vector3 object where to store the result
  2980. * @returns the unmodified current Vector3
  2981. */
  2982. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2983. result.x += this.x * scale;
  2984. result.y += this.y * scale;
  2985. result.z += this.z * scale;
  2986. return this;
  2987. };
  2988. /**
  2989. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2990. * @param otherVector defines the second operand
  2991. * @returns true if both vectors are equals
  2992. */
  2993. Vector3.prototype.equals = function (otherVector) {
  2994. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2995. };
  2996. /**
  2997. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2998. * @param otherVector defines the second operand
  2999. * @param epsilon defines the minimal distance to define values as equals
  3000. * @returns true if both vectors are distant less than epsilon
  3001. */
  3002. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3003. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3004. 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);
  3005. };
  3006. /**
  3007. * Returns true if the current Vector3 coordinates equals the given floats
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @returns true if both vectors are equals
  3012. */
  3013. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3014. return this.x === x && this.y === y && this.z === z;
  3015. };
  3016. /**
  3017. * Multiplies the current Vector3 coordinates by the given ones
  3018. * @param otherVector defines the second operand
  3019. * @returns the current updated Vector3
  3020. */
  3021. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3022. this.x *= otherVector.x;
  3023. this.y *= otherVector.y;
  3024. this.z *= otherVector.z;
  3025. return this;
  3026. };
  3027. /**
  3028. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3029. * @param otherVector defines the second operand
  3030. * @returns the new Vector3
  3031. */
  3032. Vector3.prototype.multiply = function (otherVector) {
  3033. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3034. };
  3035. /**
  3036. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3037. * @param otherVector defines the second operand
  3038. * @param result defines the Vector3 object where to store the result
  3039. * @returns the current Vector3
  3040. */
  3041. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3042. result.x = this.x * otherVector.x;
  3043. result.y = this.y * otherVector.y;
  3044. result.z = this.z * otherVector.z;
  3045. return this;
  3046. };
  3047. /**
  3048. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3049. * @param x defines the x coordinate of the operand
  3050. * @param y defines the y coordinate of the operand
  3051. * @param z defines the z coordinate of the operand
  3052. * @returns the new Vector3
  3053. */
  3054. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3055. return new Vector3(this.x * x, this.y * y, this.z * z);
  3056. };
  3057. /**
  3058. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3059. * @param otherVector defines the second operand
  3060. * @returns the new Vector3
  3061. */
  3062. Vector3.prototype.divide = function (otherVector) {
  3063. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3064. };
  3065. /**
  3066. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3067. * @param otherVector defines the second operand
  3068. * @param result defines the Vector3 object where to store the result
  3069. * @returns the current Vector3
  3070. */
  3071. Vector3.prototype.divideToRef = function (otherVector, result) {
  3072. result.x = this.x / otherVector.x;
  3073. result.y = this.y / otherVector.y;
  3074. result.z = this.z / otherVector.z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Divides the current Vector3 coordinates by the given ones.
  3079. * @param otherVector defines the second operand
  3080. * @returns the current updated Vector3
  3081. */
  3082. Vector3.prototype.divideInPlace = function (otherVector) {
  3083. return this.divideToRef(otherVector, this);
  3084. };
  3085. /**
  3086. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3087. * @param other defines the second operand
  3088. * @returns the current updated Vector3
  3089. */
  3090. Vector3.prototype.minimizeInPlace = function (other) {
  3091. if (other.x < this.x)
  3092. this.x = other.x;
  3093. if (other.y < this.y)
  3094. this.y = other.y;
  3095. if (other.z < this.z)
  3096. this.z = other.z;
  3097. return this;
  3098. };
  3099. /**
  3100. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3101. * @param other defines the second operand
  3102. * @returns the current updated Vector3
  3103. */
  3104. Vector3.prototype.maximizeInPlace = function (other) {
  3105. if (other.x > this.x)
  3106. this.x = other.x;
  3107. if (other.y > this.y)
  3108. this.y = other.y;
  3109. if (other.z > this.z)
  3110. this.z = other.z;
  3111. return this;
  3112. };
  3113. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3114. /**
  3115. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3116. */
  3117. get: function () {
  3118. var absX = Math.abs(this.x);
  3119. var absY = Math.abs(this.y);
  3120. if (absX !== absY) {
  3121. return true;
  3122. }
  3123. var absZ = Math.abs(this.z);
  3124. if (absX !== absZ) {
  3125. return true;
  3126. }
  3127. if (absY !== absZ) {
  3128. return true;
  3129. }
  3130. return false;
  3131. },
  3132. enumerable: true,
  3133. configurable: true
  3134. });
  3135. // Properties
  3136. /**
  3137. * Gets the length of the Vector3
  3138. * @returns the length of the Vecto3
  3139. */
  3140. Vector3.prototype.length = function () {
  3141. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3142. };
  3143. /**
  3144. * Gets the squared length of the Vector3
  3145. * @returns squared length of the Vector3
  3146. */
  3147. Vector3.prototype.lengthSquared = function () {
  3148. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3149. };
  3150. /**
  3151. * Normalize the current Vector3.
  3152. * Please note that this is an in place operation.
  3153. * @returns the current updated Vector3
  3154. */
  3155. Vector3.prototype.normalize = function () {
  3156. var len = this.length();
  3157. if (len === 0 || len === 1.0)
  3158. return this;
  3159. var num = 1.0 / len;
  3160. this.x *= num;
  3161. this.y *= num;
  3162. this.z *= num;
  3163. return this;
  3164. };
  3165. /**
  3166. * Normalize the current Vector3 to a new vector
  3167. * @returns the new Vector3
  3168. */
  3169. Vector3.prototype.normalizeToNew = function () {
  3170. var normalized = new Vector3(0, 0, 0);
  3171. this.normalizeToRef(normalized);
  3172. return normalized;
  3173. };
  3174. /**
  3175. * Normalize the current Vector3 to the reference
  3176. * @param reference define the Vector3 to update
  3177. * @returns the updated Vector3
  3178. */
  3179. Vector3.prototype.normalizeToRef = function (reference) {
  3180. var len = this.length();
  3181. if (len === 0 || len === 1.0) {
  3182. reference.set(this.x, this.y, this.z);
  3183. return reference;
  3184. }
  3185. var scale = 1.0 / len;
  3186. this.scaleToRef(scale, reference);
  3187. return reference;
  3188. };
  3189. /**
  3190. * Creates a new Vector3 copied from the current Vector3
  3191. * @returns the new Vector3
  3192. */
  3193. Vector3.prototype.clone = function () {
  3194. return new Vector3(this.x, this.y, this.z);
  3195. };
  3196. /**
  3197. * Copies the given vector coordinates to the current Vector3 ones
  3198. * @param source defines the source Vector3
  3199. * @returns the current updated Vector3
  3200. */
  3201. Vector3.prototype.copyFrom = function (source) {
  3202. this.x = source.x;
  3203. this.y = source.y;
  3204. this.z = source.z;
  3205. return this;
  3206. };
  3207. /**
  3208. * Copies the given floats to the current Vector3 coordinates
  3209. * @param x defines the x coordinate of the operand
  3210. * @param y defines the y coordinate of the operand
  3211. * @param z defines the z coordinate of the operand
  3212. * @returns the current updated Vector3
  3213. */
  3214. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3215. this.x = x;
  3216. this.y = y;
  3217. this.z = z;
  3218. return this;
  3219. };
  3220. /**
  3221. * Copies the given floats to the current Vector3 coordinates
  3222. * @param x defines the x coordinate of the operand
  3223. * @param y defines the y coordinate of the operand
  3224. * @param z defines the z coordinate of the operand
  3225. * @returns the current updated Vector3
  3226. */
  3227. Vector3.prototype.set = function (x, y, z) {
  3228. return this.copyFromFloats(x, y, z);
  3229. };
  3230. // Statics
  3231. /**
  3232. * Get the clip factor between two vectors
  3233. * @param vector0 defines the first operand
  3234. * @param vector1 defines the second operand
  3235. * @param axis defines the axis to use
  3236. * @param size defines the size along the axis
  3237. * @returns the clip factor
  3238. */
  3239. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3240. var d0 = Vector3.Dot(vector0, axis) - size;
  3241. var d1 = Vector3.Dot(vector1, axis) - size;
  3242. var s = d0 / (d0 - d1);
  3243. return s;
  3244. };
  3245. /**
  3246. * Get angle between two vectors
  3247. * @param vector0 angle between vector0 and vector1
  3248. * @param vector1 angle between vector0 and vector1
  3249. * @param normal direction of the normal
  3250. * @return the angle between vector0 and vector1
  3251. */
  3252. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3253. var v0 = vector0.clone().normalize();
  3254. var v1 = vector1.clone().normalize();
  3255. var dot = Vector3.Dot(v0, v1);
  3256. var n = Vector3.Cross(v0, v1);
  3257. if (Vector3.Dot(n, normal) > 0) {
  3258. return Math.acos(dot);
  3259. }
  3260. return -Math.acos(dot);
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set from the index "offset" of the given array
  3264. * @param array defines the source array
  3265. * @param offset defines the offset in the source array
  3266. * @returns the new Vector3
  3267. */
  3268. Vector3.FromArray = function (array, offset) {
  3269. if (!offset) {
  3270. offset = 0;
  3271. }
  3272. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3273. };
  3274. /**
  3275. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3276. * This function is deprecated. Use FromArray instead
  3277. * @param array defines the source array
  3278. * @param offset defines the offset in the source array
  3279. * @returns the new Vector3
  3280. */
  3281. Vector3.FromFloatArray = function (array, offset) {
  3282. return Vector3.FromArray(array, offset);
  3283. };
  3284. /**
  3285. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3286. * @param array defines the source array
  3287. * @param offset defines the offset in the source array
  3288. * @param result defines the Vector3 where to store the result
  3289. */
  3290. Vector3.FromArrayToRef = function (array, offset, result) {
  3291. result.x = array[offset];
  3292. result.y = array[offset + 1];
  3293. result.z = array[offset + 2];
  3294. };
  3295. /**
  3296. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3297. * This function is deprecated. Use FromArrayToRef instead.
  3298. * @param array defines the source array
  3299. * @param offset defines the offset in the source array
  3300. * @param result defines the Vector3 where to store the result
  3301. */
  3302. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3303. return Vector3.FromArrayToRef(array, offset, result);
  3304. };
  3305. /**
  3306. * Sets the given vector "result" with the given floats.
  3307. * @param x defines the x coordinate of the source
  3308. * @param y defines the y coordinate of the source
  3309. * @param z defines the z coordinate of the source
  3310. * @param result defines the Vector3 where to store the result
  3311. */
  3312. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3313. result.x = x;
  3314. result.y = y;
  3315. result.z = z;
  3316. };
  3317. /**
  3318. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3319. * @returns a new empty Vector3
  3320. */
  3321. Vector3.Zero = function () {
  3322. return new Vector3(0.0, 0.0, 0.0);
  3323. };
  3324. /**
  3325. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3326. * @returns a new unit Vector3
  3327. */
  3328. Vector3.One = function () {
  3329. return new Vector3(1.0, 1.0, 1.0);
  3330. };
  3331. /**
  3332. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3333. * @returns a new up Vector3
  3334. */
  3335. Vector3.Up = function () {
  3336. return new Vector3(0.0, 1.0, 0.0);
  3337. };
  3338. /**
  3339. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3340. * @returns a new down Vector3
  3341. */
  3342. Vector3.Down = function () {
  3343. return new Vector3(0.0, -1.0, 0.0);
  3344. };
  3345. /**
  3346. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3347. * @returns a new forward Vector3
  3348. */
  3349. Vector3.Forward = function () {
  3350. return new Vector3(0.0, 0.0, 1.0);
  3351. };
  3352. /**
  3353. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3354. * @returns a new right Vector3
  3355. */
  3356. Vector3.Right = function () {
  3357. return new Vector3(1.0, 0.0, 0.0);
  3358. };
  3359. /**
  3360. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3361. * @returns a new left Vector3
  3362. */
  3363. Vector3.Left = function () {
  3364. return new Vector3(-1.0, 0.0, 0.0);
  3365. };
  3366. /**
  3367. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3368. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3369. * @param vector defines the Vector3 to transform
  3370. * @param transformation defines the transformation matrix
  3371. * @returns the transformed Vector3
  3372. */
  3373. Vector3.TransformCoordinates = function (vector, transformation) {
  3374. var result = Vector3.Zero();
  3375. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3376. return result;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3380. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3381. * @param vector defines the Vector3 to transform
  3382. * @param transformation defines the transformation matrix
  3383. * @param result defines the Vector3 where to store the result
  3384. */
  3385. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3386. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3387. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3388. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3389. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3390. result.x = x / w;
  3391. result.y = y / w;
  3392. result.z = z / w;
  3393. };
  3394. /**
  3395. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3396. * This method computes tranformed coordinates only, not transformed direction vectors
  3397. * @param x define the x coordinate of the source vector
  3398. * @param y define the y coordinate of the source vector
  3399. * @param z define the z coordinate of the source vector
  3400. * @param transformation defines the transformation matrix
  3401. * @param result defines the Vector3 where to store the result
  3402. */
  3403. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3404. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3405. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3406. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3407. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3408. result.x = rx / rw;
  3409. result.y = ry / rw;
  3410. result.z = rz / rw;
  3411. };
  3412. /**
  3413. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param vector defines the Vector3 to transform
  3416. * @param transformation defines the transformation matrix
  3417. * @returns the new Vector3
  3418. */
  3419. Vector3.TransformNormal = function (vector, transformation) {
  3420. var result = Vector3.Zero();
  3421. Vector3.TransformNormalToRef(vector, transformation, result);
  3422. return result;
  3423. };
  3424. /**
  3425. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3426. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3427. * @param vector defines the Vector3 to transform
  3428. * @param transformation defines the transformation matrix
  3429. * @param result defines the Vector3 where to store the result
  3430. */
  3431. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3432. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3433. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3434. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3435. result.x = x;
  3436. result.y = y;
  3437. result.z = z;
  3438. };
  3439. /**
  3440. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3441. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3442. * @param x define the x coordinate of the source vector
  3443. * @param y define the y coordinate of the source vector
  3444. * @param z define the z coordinate of the source vector
  3445. * @param transformation defines the transformation matrix
  3446. * @param result defines the Vector3 where to store the result
  3447. */
  3448. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3449. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3450. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3451. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3452. };
  3453. /**
  3454. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3455. * @param value1 defines the first control point
  3456. * @param value2 defines the second control point
  3457. * @param value3 defines the third control point
  3458. * @param value4 defines the fourth control point
  3459. * @param amount defines the amount on the spline to use
  3460. * @returns the new Vector3
  3461. */
  3462. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3463. var squared = amount * amount;
  3464. var cubed = amount * squared;
  3465. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3466. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3467. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3468. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3469. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3470. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3471. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3472. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3473. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3474. return new Vector3(x, y, z);
  3475. };
  3476. /**
  3477. * 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"
  3478. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3479. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3480. * @param value defines the current value
  3481. * @param min defines the lower range value
  3482. * @param max defines the upper range value
  3483. * @returns the new Vector3
  3484. */
  3485. Vector3.Clamp = function (value, min, max) {
  3486. var x = value.x;
  3487. x = (x > max.x) ? max.x : x;
  3488. x = (x < min.x) ? min.x : x;
  3489. var y = value.y;
  3490. y = (y > max.y) ? max.y : y;
  3491. y = (y < min.y) ? min.y : y;
  3492. var z = value.z;
  3493. z = (z > max.z) ? max.z : z;
  3494. z = (z < min.z) ? min.z : z;
  3495. return new Vector3(x, y, z);
  3496. };
  3497. /**
  3498. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3499. * @param value1 defines the first control point
  3500. * @param tangent1 defines the first tangent vector
  3501. * @param value2 defines the second control point
  3502. * @param tangent2 defines the second tangent vector
  3503. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3504. * @returns the new Vector3
  3505. */
  3506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3507. var squared = amount * amount;
  3508. var cubed = amount * squared;
  3509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3511. var part3 = (cubed - (2.0 * squared)) + amount;
  3512. var part4 = cubed - squared;
  3513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3516. return new Vector3(x, y, z);
  3517. };
  3518. /**
  3519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3520. * @param start defines the start value
  3521. * @param end defines the end value
  3522. * @param amount max defines amount between both (between 0 and 1)
  3523. * @returns the new Vector3
  3524. */
  3525. Vector3.Lerp = function (start, end, amount) {
  3526. var result = new Vector3(0, 0, 0);
  3527. Vector3.LerpToRef(start, end, amount, result);
  3528. return result;
  3529. };
  3530. /**
  3531. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3532. * @param start defines the start value
  3533. * @param end defines the end value
  3534. * @param amount max defines amount between both (between 0 and 1)
  3535. * @param result defines the Vector3 where to store the result
  3536. */
  3537. Vector3.LerpToRef = function (start, end, amount, result) {
  3538. result.x = start.x + ((end.x - start.x) * amount);
  3539. result.y = start.y + ((end.y - start.y) * amount);
  3540. result.z = start.z + ((end.z - start.z) * amount);
  3541. };
  3542. /**
  3543. * Returns the dot product (float) between the vectors "left" and "right"
  3544. * @param left defines the left operand
  3545. * @param right defines the right operand
  3546. * @returns the dot product
  3547. */
  3548. Vector3.Dot = function (left, right) {
  3549. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3550. };
  3551. /**
  3552. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3553. * The cross product is then orthogonal to both "left" and "right"
  3554. * @param left defines the left operand
  3555. * @param right defines the right operand
  3556. * @returns the cross product
  3557. */
  3558. Vector3.Cross = function (left, right) {
  3559. var result = Vector3.Zero();
  3560. Vector3.CrossToRef(left, right, result);
  3561. return result;
  3562. };
  3563. /**
  3564. * Sets the given vector "result" with the cross product of "left" and "right"
  3565. * The cross product is then orthogonal to both "left" and "right"
  3566. * @param left defines the left operand
  3567. * @param right defines the right operand
  3568. * @param result defines the Vector3 where to store the result
  3569. */
  3570. Vector3.CrossToRef = function (left, right, result) {
  3571. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3572. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3573. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3574. result.copyFrom(MathTmp.Vector3[0]);
  3575. };
  3576. /**
  3577. * Returns a new Vector3 as the normalization of the given vector
  3578. * @param vector defines the Vector3 to normalize
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.Normalize = function (vector) {
  3582. var result = Vector3.Zero();
  3583. Vector3.NormalizeToRef(vector, result);
  3584. return result;
  3585. };
  3586. /**
  3587. * Sets the given vector "result" with the normalization of the given first vector
  3588. * @param vector defines the Vector3 to normalize
  3589. * @param result defines the Vector3 where to store the result
  3590. */
  3591. Vector3.NormalizeToRef = function (vector, result) {
  3592. result.copyFrom(vector);
  3593. result.normalize();
  3594. };
  3595. /**
  3596. * Project a Vector3 onto screen space
  3597. * @param vector defines the Vector3 to project
  3598. * @param world defines the world matrix to use
  3599. * @param transform defines the transform (view x projection) matrix to use
  3600. * @param viewport defines the screen viewport to use
  3601. * @returns the new Vector3
  3602. */
  3603. Vector3.Project = function (vector, world, transform, viewport) {
  3604. var cw = viewport.width;
  3605. var ch = viewport.height;
  3606. var cx = viewport.x;
  3607. var cy = viewport.y;
  3608. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3609. 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);
  3610. var matrix = MathTmp.Matrix[0];
  3611. world.multiplyToRef(transform, matrix);
  3612. matrix.multiplyToRef(viewportMatrix, matrix);
  3613. return Vector3.TransformCoordinates(vector, matrix);
  3614. };
  3615. /**
  3616. * Unproject from screen space to object space
  3617. * @param source defines the screen space Vector3 to use
  3618. * @param viewportWidth defines the current width of the viewport
  3619. * @param viewportHeight defines the current height of the viewport
  3620. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3621. * @param transform defines the transform (view x projection) matrix to use
  3622. * @returns the new Vector3
  3623. */
  3624. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3625. var matrix = MathTmp.Matrix[0];
  3626. world.multiplyToRef(transform, matrix);
  3627. matrix.invert();
  3628. source.x = source.x / viewportWidth * 2 - 1;
  3629. source.y = -(source.y / viewportHeight * 2 - 1);
  3630. var vector = Vector3.TransformCoordinates(source, matrix);
  3631. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3632. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3633. vector = vector.scale(1.0 / num);
  3634. }
  3635. return vector;
  3636. };
  3637. /**
  3638. * Unproject from screen space to object space
  3639. * @param source defines the screen space Vector3 to use
  3640. * @param viewportWidth defines the current width of the viewport
  3641. * @param viewportHeight defines the current height of the viewport
  3642. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3643. * @param view defines the view matrix to use
  3644. * @param projection defines the projection matrix to use
  3645. * @returns the new Vector3
  3646. */
  3647. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3648. var result = Vector3.Zero();
  3649. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3650. return result;
  3651. };
  3652. /**
  3653. * Unproject from screen space to object space
  3654. * @param source defines the screen space Vector3 to use
  3655. * @param viewportWidth defines the current width of the viewport
  3656. * @param viewportHeight defines the current height of the viewport
  3657. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3658. * @param view defines the view matrix to use
  3659. * @param projection defines the projection matrix to use
  3660. * @param result defines the Vector3 where to store the result
  3661. */
  3662. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3663. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3664. };
  3665. /**
  3666. * Unproject from screen space to object space
  3667. * @param sourceX defines the screen space x coordinate to use
  3668. * @param sourceY defines the screen space y coordinate to use
  3669. * @param sourceZ defines the screen space z coordinate to use
  3670. * @param viewportWidth defines the current width of the viewport
  3671. * @param viewportHeight defines the current height of the viewport
  3672. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3673. * @param view defines the view matrix to use
  3674. * @param projection defines the projection matrix to use
  3675. * @param result defines the Vector3 where to store the result
  3676. */
  3677. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3678. var matrix = MathTmp.Matrix[0];
  3679. world.multiplyToRef(view, matrix);
  3680. matrix.multiplyToRef(projection, matrix);
  3681. matrix.invert();
  3682. var screenSource = MathTmp.Vector3[0];
  3683. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3684. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3685. screenSource.z = 2 * sourceZ - 1.0;
  3686. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3687. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3688. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3689. result.scaleInPlace(1.0 / num);
  3690. }
  3691. };
  3692. /**
  3693. * Gets the minimal coordinate values between two Vector3
  3694. * @param left defines the first operand
  3695. * @param right defines the second operand
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Minimize = function (left, right) {
  3699. var min = left.clone();
  3700. min.minimizeInPlace(right);
  3701. return min;
  3702. };
  3703. /**
  3704. * Gets the maximal coordinate values between two Vector3
  3705. * @param left defines the first operand
  3706. * @param right defines the second operand
  3707. * @returns the new Vector3
  3708. */
  3709. Vector3.Maximize = function (left, right) {
  3710. var max = left.clone();
  3711. max.maximizeInPlace(right);
  3712. return max;
  3713. };
  3714. /**
  3715. * Returns the distance between the vectors "value1" and "value2"
  3716. * @param value1 defines the first operand
  3717. * @param value2 defines the second operand
  3718. * @returns the distance
  3719. */
  3720. Vector3.Distance = function (value1, value2) {
  3721. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3722. };
  3723. /**
  3724. * Returns the squared distance between the vectors "value1" and "value2"
  3725. * @param value1 defines the first operand
  3726. * @param value2 defines the second operand
  3727. * @returns the squared distance
  3728. */
  3729. Vector3.DistanceSquared = function (value1, value2) {
  3730. var x = value1.x - value2.x;
  3731. var y = value1.y - value2.y;
  3732. var z = value1.z - value2.z;
  3733. return (x * x) + (y * y) + (z * z);
  3734. };
  3735. /**
  3736. * Returns a new Vector3 located at the center between "value1" and "value2"
  3737. * @param value1 defines the first operand
  3738. * @param value2 defines the second operand
  3739. * @returns the new Vector3
  3740. */
  3741. Vector3.Center = function (value1, value2) {
  3742. var center = value1.add(value2);
  3743. center.scaleInPlace(0.5);
  3744. return center;
  3745. };
  3746. /**
  3747. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3748. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3749. * to something in order to rotate it from its local system to the given target system
  3750. * Note: axis1, axis2 and axis3 are normalized during this operation
  3751. * @param axis1 defines the first axis
  3752. * @param axis2 defines the second axis
  3753. * @param axis3 defines the third axis
  3754. * @returns a new Vector3
  3755. */
  3756. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3757. var rotation = Vector3.Zero();
  3758. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3759. return rotation;
  3760. };
  3761. /**
  3762. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3763. * @param axis1 defines the first axis
  3764. * @param axis2 defines the second axis
  3765. * @param axis3 defines the third axis
  3766. * @param ref defines the Vector3 where to store the result
  3767. */
  3768. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3769. var quat = MathTmp.Quaternion[0];
  3770. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3771. quat.toEulerAnglesToRef(ref);
  3772. };
  3773. return Vector3;
  3774. }());
  3775. BABYLON.Vector3 = Vector3;
  3776. //Vector4 class created for EulerAngle class conversion to Quaternion
  3777. var Vector4 = /** @class */ (function () {
  3778. /**
  3779. * Creates a Vector4 object from the given floats.
  3780. */
  3781. function Vector4(x, y, z, w) {
  3782. this.x = x;
  3783. this.y = y;
  3784. this.z = z;
  3785. this.w = w;
  3786. }
  3787. /**
  3788. * Returns the string with the Vector4 coordinates.
  3789. */
  3790. Vector4.prototype.toString = function () {
  3791. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3792. };
  3793. /**
  3794. * Returns the string "Vector4".
  3795. */
  3796. Vector4.prototype.getClassName = function () {
  3797. return "Vector4";
  3798. };
  3799. /**
  3800. * Returns the Vector4 hash code.
  3801. */
  3802. Vector4.prototype.getHashCode = function () {
  3803. var hash = this.x || 0;
  3804. hash = (hash * 397) ^ (this.y || 0);
  3805. hash = (hash * 397) ^ (this.z || 0);
  3806. hash = (hash * 397) ^ (this.w || 0);
  3807. return hash;
  3808. };
  3809. // Operators
  3810. /**
  3811. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3812. */
  3813. Vector4.prototype.asArray = function () {
  3814. var result = new Array();
  3815. this.toArray(result, 0);
  3816. return result;
  3817. };
  3818. /**
  3819. * Populates the given array from the given index with the Vector4 coordinates.
  3820. * Returns the Vector4.
  3821. */
  3822. Vector4.prototype.toArray = function (array, index) {
  3823. if (index === undefined) {
  3824. index = 0;
  3825. }
  3826. array[index] = this.x;
  3827. array[index + 1] = this.y;
  3828. array[index + 2] = this.z;
  3829. array[index + 3] = this.w;
  3830. return this;
  3831. };
  3832. /**
  3833. * Adds the given vector to the current Vector4.
  3834. * Returns the updated Vector4.
  3835. */
  3836. Vector4.prototype.addInPlace = function (otherVector) {
  3837. this.x += otherVector.x;
  3838. this.y += otherVector.y;
  3839. this.z += otherVector.z;
  3840. this.w += otherVector.w;
  3841. return this;
  3842. };
  3843. /**
  3844. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3845. */
  3846. Vector4.prototype.add = function (otherVector) {
  3847. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3848. };
  3849. /**
  3850. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3851. * Returns the current Vector4.
  3852. */
  3853. Vector4.prototype.addToRef = function (otherVector, result) {
  3854. result.x = this.x + otherVector.x;
  3855. result.y = this.y + otherVector.y;
  3856. result.z = this.z + otherVector.z;
  3857. result.w = this.w + otherVector.w;
  3858. return this;
  3859. };
  3860. /**
  3861. * Subtract in place the given vector from the current Vector4.
  3862. * Returns the updated Vector4.
  3863. */
  3864. Vector4.prototype.subtractInPlace = function (otherVector) {
  3865. this.x -= otherVector.x;
  3866. this.y -= otherVector.y;
  3867. this.z -= otherVector.z;
  3868. this.w -= otherVector.w;
  3869. return this;
  3870. };
  3871. /**
  3872. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3873. */
  3874. Vector4.prototype.subtract = function (otherVector) {
  3875. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3876. };
  3877. /**
  3878. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3879. * Returns the current Vector4.
  3880. */
  3881. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3882. result.x = this.x - otherVector.x;
  3883. result.y = this.y - otherVector.y;
  3884. result.z = this.z - otherVector.z;
  3885. result.w = this.w - otherVector.w;
  3886. return this;
  3887. };
  3888. /**
  3889. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3890. */
  3891. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3892. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3893. };
  3894. /**
  3895. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3896. * Returns the current Vector4.
  3897. */
  3898. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3899. result.x = this.x - x;
  3900. result.y = this.y - y;
  3901. result.z = this.z - z;
  3902. result.w = this.w - w;
  3903. return this;
  3904. };
  3905. /**
  3906. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3907. */
  3908. Vector4.prototype.negate = function () {
  3909. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3910. };
  3911. /**
  3912. * Multiplies the current Vector4 coordinates by scale (float).
  3913. * Returns the updated Vector4.
  3914. */
  3915. Vector4.prototype.scaleInPlace = function (scale) {
  3916. this.x *= scale;
  3917. this.y *= scale;
  3918. this.z *= scale;
  3919. this.w *= scale;
  3920. return this;
  3921. };
  3922. /**
  3923. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3924. */
  3925. Vector4.prototype.scale = function (scale) {
  3926. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3927. };
  3928. /**
  3929. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3930. * Returns the current Vector4.
  3931. */
  3932. Vector4.prototype.scaleToRef = function (scale, result) {
  3933. result.x = this.x * scale;
  3934. result.y = this.y * scale;
  3935. result.z = this.z * scale;
  3936. result.w = this.w * scale;
  3937. return this;
  3938. };
  3939. /**
  3940. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3941. * @param scale defines the scale factor
  3942. * @param result defines the Vector4 object where to store the result
  3943. * @returns the unmodified current Vector4
  3944. */
  3945. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3946. result.x += this.x * scale;
  3947. result.y += this.y * scale;
  3948. result.z += this.z * scale;
  3949. result.w += this.w * scale;
  3950. return this;
  3951. };
  3952. /**
  3953. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3954. */
  3955. Vector4.prototype.equals = function (otherVector) {
  3956. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3957. };
  3958. /**
  3959. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3960. */
  3961. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3962. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3963. return otherVector
  3964. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3965. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3966. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3967. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3968. };
  3969. /**
  3970. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3971. */
  3972. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3973. return this.x === x && this.y === y && this.z === z && this.w === w;
  3974. };
  3975. /**
  3976. * Multiplies in place the current Vector4 by the given one.
  3977. * Returns the updated Vector4.
  3978. */
  3979. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3980. this.x *= otherVector.x;
  3981. this.y *= otherVector.y;
  3982. this.z *= otherVector.z;
  3983. this.w *= otherVector.w;
  3984. return this;
  3985. };
  3986. /**
  3987. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3988. */
  3989. Vector4.prototype.multiply = function (otherVector) {
  3990. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3991. };
  3992. /**
  3993. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3994. * Returns the current Vector4.
  3995. */
  3996. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3997. result.x = this.x * otherVector.x;
  3998. result.y = this.y * otherVector.y;
  3999. result.z = this.z * otherVector.z;
  4000. result.w = this.w * otherVector.w;
  4001. return this;
  4002. };
  4003. /**
  4004. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4005. */
  4006. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4007. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4008. };
  4009. /**
  4010. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4011. */
  4012. Vector4.prototype.divide = function (otherVector) {
  4013. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4014. };
  4015. /**
  4016. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4017. * Returns the current Vector4.
  4018. */
  4019. Vector4.prototype.divideToRef = function (otherVector, result) {
  4020. result.x = this.x / otherVector.x;
  4021. result.y = this.y / otherVector.y;
  4022. result.z = this.z / otherVector.z;
  4023. result.w = this.w / otherVector.w;
  4024. return this;
  4025. };
  4026. /**
  4027. * Divides the current Vector3 coordinates by the given ones.
  4028. * @returns the updated Vector3.
  4029. */
  4030. Vector4.prototype.divideInPlace = function (otherVector) {
  4031. return this.divideToRef(otherVector, this);
  4032. };
  4033. /**
  4034. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4035. * @param other defines the second operand
  4036. * @returns the current updated Vector4
  4037. */
  4038. Vector4.prototype.minimizeInPlace = function (other) {
  4039. if (other.x < this.x)
  4040. this.x = other.x;
  4041. if (other.y < this.y)
  4042. this.y = other.y;
  4043. if (other.z < this.z)
  4044. this.z = other.z;
  4045. if (other.w < this.w)
  4046. this.w = other.w;
  4047. return this;
  4048. };
  4049. /**
  4050. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4051. * @param other defines the second operand
  4052. * @returns the current updated Vector4
  4053. */
  4054. Vector4.prototype.maximizeInPlace = function (other) {
  4055. if (other.x > this.x)
  4056. this.x = other.x;
  4057. if (other.y > this.y)
  4058. this.y = other.y;
  4059. if (other.z > this.z)
  4060. this.z = other.z;
  4061. if (other.w > this.w)
  4062. this.w = other.w;
  4063. return this;
  4064. };
  4065. // Properties
  4066. /**
  4067. * Returns the Vector4 length (float).
  4068. */
  4069. Vector4.prototype.length = function () {
  4070. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4071. };
  4072. /**
  4073. * Returns the Vector4 squared length (float).
  4074. */
  4075. Vector4.prototype.lengthSquared = function () {
  4076. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4077. };
  4078. // Methods
  4079. /**
  4080. * Normalizes in place the Vector4.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.normalize = function () {
  4084. var len = this.length();
  4085. if (len === 0)
  4086. return this;
  4087. var num = 1.0 / len;
  4088. this.x *= num;
  4089. this.y *= num;
  4090. this.z *= num;
  4091. this.w *= num;
  4092. return this;
  4093. };
  4094. /**
  4095. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4096. */
  4097. Vector4.prototype.toVector3 = function () {
  4098. return new Vector3(this.x, this.y, this.z);
  4099. };
  4100. /**
  4101. * Returns a new Vector4 copied from the current one.
  4102. */
  4103. Vector4.prototype.clone = function () {
  4104. return new Vector4(this.x, this.y, this.z, this.w);
  4105. };
  4106. /**
  4107. * Updates the current Vector4 with the given one coordinates.
  4108. * Returns the updated Vector4.
  4109. */
  4110. Vector4.prototype.copyFrom = function (source) {
  4111. this.x = source.x;
  4112. this.y = source.y;
  4113. this.z = source.z;
  4114. this.w = source.w;
  4115. return this;
  4116. };
  4117. /**
  4118. * Updates the current Vector4 coordinates with the given floats.
  4119. * Returns the updated Vector4.
  4120. */
  4121. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4122. this.x = x;
  4123. this.y = y;
  4124. this.z = z;
  4125. this.w = w;
  4126. return this;
  4127. };
  4128. /**
  4129. * Updates the current Vector4 coordinates with the given floats.
  4130. * Returns the updated Vector4.
  4131. */
  4132. Vector4.prototype.set = function (x, y, z, w) {
  4133. return this.copyFromFloats(x, y, z, w);
  4134. };
  4135. // Statics
  4136. /**
  4137. * Returns a new Vector4 set from the starting index of the given array.
  4138. */
  4139. Vector4.FromArray = function (array, offset) {
  4140. if (!offset) {
  4141. offset = 0;
  4142. }
  4143. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4144. };
  4145. /**
  4146. * Updates the given vector "result" from the starting index of the given array.
  4147. */
  4148. Vector4.FromArrayToRef = function (array, offset, result) {
  4149. result.x = array[offset];
  4150. result.y = array[offset + 1];
  4151. result.z = array[offset + 2];
  4152. result.w = array[offset + 3];
  4153. };
  4154. /**
  4155. * Updates the given vector "result" from the starting index of the given Float32Array.
  4156. */
  4157. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4158. Vector4.FromArrayToRef(array, offset, result);
  4159. };
  4160. /**
  4161. * Updates the given vector "result" coordinates from the given floats.
  4162. */
  4163. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4164. result.x = x;
  4165. result.y = y;
  4166. result.z = z;
  4167. result.w = w;
  4168. };
  4169. /**
  4170. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4171. */
  4172. Vector4.Zero = function () {
  4173. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4174. };
  4175. /**
  4176. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4177. */
  4178. Vector4.One = function () {
  4179. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4180. };
  4181. /**
  4182. * Returns a new normalized Vector4 from the given one.
  4183. */
  4184. Vector4.Normalize = function (vector) {
  4185. var result = Vector4.Zero();
  4186. Vector4.NormalizeToRef(vector, result);
  4187. return result;
  4188. };
  4189. /**
  4190. * Updates the given vector "result" from the normalization of the given one.
  4191. */
  4192. Vector4.NormalizeToRef = function (vector, result) {
  4193. result.copyFrom(vector);
  4194. result.normalize();
  4195. };
  4196. Vector4.Minimize = function (left, right) {
  4197. var min = left.clone();
  4198. min.minimizeInPlace(right);
  4199. return min;
  4200. };
  4201. Vector4.Maximize = function (left, right) {
  4202. var max = left.clone();
  4203. max.maximizeInPlace(right);
  4204. return max;
  4205. };
  4206. /**
  4207. * Returns the distance (float) between the vectors "value1" and "value2".
  4208. */
  4209. Vector4.Distance = function (value1, value2) {
  4210. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4211. };
  4212. /**
  4213. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4214. */
  4215. Vector4.DistanceSquared = function (value1, value2) {
  4216. var x = value1.x - value2.x;
  4217. var y = value1.y - value2.y;
  4218. var z = value1.z - value2.z;
  4219. var w = value1.w - value2.w;
  4220. return (x * x) + (y * y) + (z * z) + (w * w);
  4221. };
  4222. /**
  4223. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4224. */
  4225. Vector4.Center = function (value1, value2) {
  4226. var center = value1.add(value2);
  4227. center.scaleInPlace(0.5);
  4228. return center;
  4229. };
  4230. /**
  4231. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4232. * This methods computes transformed normalized direction vectors only.
  4233. */
  4234. Vector4.TransformNormal = function (vector, transformation) {
  4235. var result = Vector4.Zero();
  4236. Vector4.TransformNormalToRef(vector, transformation, result);
  4237. return result;
  4238. };
  4239. /**
  4240. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4241. * This methods computes transformed normalized direction vectors only.
  4242. */
  4243. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4244. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4245. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4246. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4247. result.x = x;
  4248. result.y = y;
  4249. result.z = z;
  4250. result.w = vector.w;
  4251. };
  4252. /**
  4253. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4254. * This methods computes transformed normalized direction vectors only.
  4255. */
  4256. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4257. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4258. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4259. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4260. result.w = w;
  4261. };
  4262. return Vector4;
  4263. }());
  4264. BABYLON.Vector4 = Vector4;
  4265. var Size = /** @class */ (function () {
  4266. /**
  4267. * Creates a Size object from the given width and height (floats).
  4268. */
  4269. function Size(width, height) {
  4270. this.width = width;
  4271. this.height = height;
  4272. }
  4273. // Returns a string with the Size width and height.
  4274. Size.prototype.toString = function () {
  4275. return "{W: " + this.width + ", H: " + this.height + "}";
  4276. };
  4277. /**
  4278. * Returns the string "Size"
  4279. */
  4280. Size.prototype.getClassName = function () {
  4281. return "Size";
  4282. };
  4283. /**
  4284. * Returns the Size hash code.
  4285. */
  4286. Size.prototype.getHashCode = function () {
  4287. var hash = this.width || 0;
  4288. hash = (hash * 397) ^ (this.height || 0);
  4289. return hash;
  4290. };
  4291. /**
  4292. * Updates the current size from the given one.
  4293. * Returns the updated Size.
  4294. */
  4295. Size.prototype.copyFrom = function (src) {
  4296. this.width = src.width;
  4297. this.height = src.height;
  4298. };
  4299. /**
  4300. * Updates in place the current Size from the given floats.
  4301. * Returns the updated Size.
  4302. */
  4303. Size.prototype.copyFromFloats = function (width, height) {
  4304. this.width = width;
  4305. this.height = height;
  4306. return this;
  4307. };
  4308. /**
  4309. * Updates in place the current Size from the given floats.
  4310. * Returns the updated Size.
  4311. */
  4312. Size.prototype.set = function (width, height) {
  4313. return this.copyFromFloats(width, height);
  4314. };
  4315. /**
  4316. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4317. */
  4318. Size.prototype.multiplyByFloats = function (w, h) {
  4319. return new Size(this.width * w, this.height * h);
  4320. };
  4321. /**
  4322. * Returns a new Size copied from the given one.
  4323. */
  4324. Size.prototype.clone = function () {
  4325. return new Size(this.width, this.height);
  4326. };
  4327. /**
  4328. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4329. */
  4330. Size.prototype.equals = function (other) {
  4331. if (!other) {
  4332. return false;
  4333. }
  4334. return (this.width === other.width) && (this.height === other.height);
  4335. };
  4336. Object.defineProperty(Size.prototype, "surface", {
  4337. /**
  4338. * Returns the surface of the Size : width * height (float).
  4339. */
  4340. get: function () {
  4341. return this.width * this.height;
  4342. },
  4343. enumerable: true,
  4344. configurable: true
  4345. });
  4346. /**
  4347. * Returns a new Size set to (0.0, 0.0)
  4348. */
  4349. Size.Zero = function () {
  4350. return new Size(0.0, 0.0);
  4351. };
  4352. /**
  4353. * Returns a new Size set as the addition result of the current Size and the given one.
  4354. */
  4355. Size.prototype.add = function (otherSize) {
  4356. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4357. return r;
  4358. };
  4359. /**
  4360. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4361. */
  4362. Size.prototype.subtract = function (otherSize) {
  4363. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4364. return r;
  4365. };
  4366. /**
  4367. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4368. */
  4369. Size.Lerp = function (start, end, amount) {
  4370. var w = start.width + ((end.width - start.width) * amount);
  4371. var h = start.height + ((end.height - start.height) * amount);
  4372. return new Size(w, h);
  4373. };
  4374. return Size;
  4375. }());
  4376. BABYLON.Size = Size;
  4377. /**
  4378. * Class used to store quaternion data
  4379. * @see https://en.wikipedia.org/wiki/Quaternion
  4380. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4381. */
  4382. var Quaternion = /** @class */ (function () {
  4383. /**
  4384. * Creates a new Quaternion from the given floats
  4385. * @param x defines the first component (0 by default)
  4386. * @param y defines the second component (0 by default)
  4387. * @param z defines the third component (0 by default)
  4388. * @param w defines the fourth component (1.0 by default)
  4389. */
  4390. function Quaternion(
  4391. /** defines the first component (0 by default) */
  4392. x,
  4393. /** defines the second component (0 by default) */
  4394. y,
  4395. /** defines the third component (0 by default) */
  4396. z,
  4397. /** defines the fourth component (1.0 by default) */
  4398. w) {
  4399. if (x === void 0) { x = 0.0; }
  4400. if (y === void 0) { y = 0.0; }
  4401. if (z === void 0) { z = 0.0; }
  4402. if (w === void 0) { w = 1.0; }
  4403. this.x = x;
  4404. this.y = y;
  4405. this.z = z;
  4406. this.w = w;
  4407. }
  4408. /**
  4409. * Gets a string representation for the current quaternion
  4410. * @returns a string with the Quaternion coordinates
  4411. */
  4412. Quaternion.prototype.toString = function () {
  4413. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4414. };
  4415. /**
  4416. * Gets the class name of the quaternion
  4417. * @returns the string "Quaternion"
  4418. */
  4419. Quaternion.prototype.getClassName = function () {
  4420. return "Quaternion";
  4421. };
  4422. /**
  4423. * Gets a hash code for this quaternion
  4424. * @returns the quaternion hash code
  4425. */
  4426. Quaternion.prototype.getHashCode = function () {
  4427. var hash = this.x || 0;
  4428. hash = (hash * 397) ^ (this.y || 0);
  4429. hash = (hash * 397) ^ (this.z || 0);
  4430. hash = (hash * 397) ^ (this.w || 0);
  4431. return hash;
  4432. };
  4433. /**
  4434. * Copy the quaternion to an array
  4435. * @returns a new array populated with 4 elements from the quaternion coordinates
  4436. */
  4437. Quaternion.prototype.asArray = function () {
  4438. return [this.x, this.y, this.z, this.w];
  4439. };
  4440. /**
  4441. * Check if two quaternions are equals
  4442. * @param otherQuaternion defines the second operand
  4443. * @return true if the current quaternion and the given one coordinates are strictly equals
  4444. */
  4445. Quaternion.prototype.equals = function (otherQuaternion) {
  4446. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4447. };
  4448. /**
  4449. * Clone the current quaternion
  4450. * @returns a new quaternion copied from the current one
  4451. */
  4452. Quaternion.prototype.clone = function () {
  4453. return new Quaternion(this.x, this.y, this.z, this.w);
  4454. };
  4455. /**
  4456. * Copy a quaternion to the current one
  4457. * @param other defines the other quaternion
  4458. * @returns the updated current quaternion
  4459. */
  4460. Quaternion.prototype.copyFrom = function (other) {
  4461. this.x = other.x;
  4462. this.y = other.y;
  4463. this.z = other.z;
  4464. this.w = other.w;
  4465. return this;
  4466. };
  4467. /**
  4468. * Updates the current quaternion with the given float coordinates
  4469. * @param x defines the x coordinate
  4470. * @param y defines the y coordinate
  4471. * @param z defines the z coordinate
  4472. * @param w defines the w coordinate
  4473. * @returns the updated current quaternion
  4474. */
  4475. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4476. this.x = x;
  4477. this.y = y;
  4478. this.z = z;
  4479. this.w = w;
  4480. return this;
  4481. };
  4482. /**
  4483. * Updates the current quaternion from the given float coordinates
  4484. * @param x defines the x coordinate
  4485. * @param y defines the y coordinate
  4486. * @param z defines the z coordinate
  4487. * @param w defines the w coordinate
  4488. * @returns the updated current quaternion
  4489. */
  4490. Quaternion.prototype.set = function (x, y, z, w) {
  4491. return this.copyFromFloats(x, y, z, w);
  4492. };
  4493. /**
  4494. * Adds two quaternions
  4495. * @param other defines the second operand
  4496. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4497. */
  4498. Quaternion.prototype.add = function (other) {
  4499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4500. };
  4501. /**
  4502. * Add a quaternion to the current one
  4503. * @param other defines the quaternion to add
  4504. * @returns the current quaternion
  4505. */
  4506. Quaternion.prototype.addInPlace = function (other) {
  4507. this.x += other.x;
  4508. this.y += other.y;
  4509. this.z += other.z;
  4510. this.w += other.w;
  4511. return this;
  4512. };
  4513. /**
  4514. * Subtract two quaternions
  4515. * @param other defines the second operand
  4516. * @returns a new quaternion as the subtraction result of the given one from the current one
  4517. */
  4518. Quaternion.prototype.subtract = function (other) {
  4519. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4520. };
  4521. /**
  4522. * Multiplies the current quaternion by a scale factor
  4523. * @param value defines the scale factor
  4524. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4525. */
  4526. Quaternion.prototype.scale = function (value) {
  4527. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4528. };
  4529. /**
  4530. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4531. * @param scale defines the scale factor
  4532. * @param result defines the Quaternion object where to store the result
  4533. * @returns the unmodified current quaternion
  4534. */
  4535. Quaternion.prototype.scaleToRef = function (scale, result) {
  4536. result.x = this.x * scale;
  4537. result.y = this.y * scale;
  4538. result.z = this.z * scale;
  4539. result.w = this.w * scale;
  4540. return this;
  4541. };
  4542. /**
  4543. * Multiplies in place the current quaternion by a scale factor
  4544. * @param value defines the scale factor
  4545. * @returns the current modified quaternion
  4546. */
  4547. Quaternion.prototype.scaleInPlace = function (value) {
  4548. this.x *= value;
  4549. this.y *= value;
  4550. this.z *= value;
  4551. this.w *= value;
  4552. return this;
  4553. };
  4554. /**
  4555. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4556. * @param scale defines the scale factor
  4557. * @param result defines the Quaternion object where to store the result
  4558. * @returns the unmodified current quaternion
  4559. */
  4560. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4561. result.x += this.x * scale;
  4562. result.y += this.y * scale;
  4563. result.z += this.z * scale;
  4564. result.w += this.w * scale;
  4565. return this;
  4566. };
  4567. /**
  4568. * Multiplies two quaternions
  4569. * @param q1 defines the second operand
  4570. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4571. */
  4572. Quaternion.prototype.multiply = function (q1) {
  4573. var result = new Quaternion(0, 0, 0, 1.0);
  4574. this.multiplyToRef(q1, result);
  4575. return result;
  4576. };
  4577. /**
  4578. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4579. * @param q1 defines the second operand
  4580. * @param result defines the target quaternion
  4581. * @returns the current quaternion
  4582. */
  4583. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4584. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4585. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4586. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4587. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4588. result.copyFromFloats(x, y, z, w);
  4589. return this;
  4590. };
  4591. /**
  4592. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4593. * @param q1 defines the second operand
  4594. * @returns the currentupdated quaternion
  4595. */
  4596. Quaternion.prototype.multiplyInPlace = function (q1) {
  4597. this.multiplyToRef(q1, this);
  4598. return this;
  4599. };
  4600. /**
  4601. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4602. * @param ref defines the target quaternion
  4603. * @returns the current quaternion
  4604. */
  4605. Quaternion.prototype.conjugateToRef = function (ref) {
  4606. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4607. return this;
  4608. };
  4609. /**
  4610. * Conjugates in place (1-q) the current quaternion
  4611. * @returns the current updated quaternion
  4612. */
  4613. Quaternion.prototype.conjugateInPlace = function () {
  4614. this.x *= -1;
  4615. this.y *= -1;
  4616. this.z *= -1;
  4617. return this;
  4618. };
  4619. /**
  4620. * Conjugates in place (1-q) the current quaternion
  4621. * @returns a new quaternion
  4622. */
  4623. Quaternion.prototype.conjugate = function () {
  4624. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4625. return result;
  4626. };
  4627. /**
  4628. * Gets length of current quaternion
  4629. * @returns the quaternion length (float)
  4630. */
  4631. Quaternion.prototype.length = function () {
  4632. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4633. };
  4634. /**
  4635. * Normalize in place the current quaternion
  4636. * @returns the current updated quaternion
  4637. */
  4638. Quaternion.prototype.normalize = function () {
  4639. var length = 1.0 / this.length();
  4640. this.x *= length;
  4641. this.y *= length;
  4642. this.z *= length;
  4643. this.w *= length;
  4644. return this;
  4645. };
  4646. /**
  4647. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4648. * @param order is a reserved parameter and is ignore for now
  4649. * @returns a new Vector3 containing the Euler angles
  4650. */
  4651. Quaternion.prototype.toEulerAngles = function (order) {
  4652. if (order === void 0) { order = "YZX"; }
  4653. var result = Vector3.Zero();
  4654. this.toEulerAnglesToRef(result, order);
  4655. return result;
  4656. };
  4657. /**
  4658. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4659. * @param result defines the vector which will be filled with the Euler angles
  4660. * @param order is a reserved parameter and is ignore for now
  4661. * @returns the current unchanged quaternion
  4662. */
  4663. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4664. if (order === void 0) { order = "YZX"; }
  4665. var qz = this.z;
  4666. var qx = this.x;
  4667. var qy = this.y;
  4668. var qw = this.w;
  4669. var sqw = qw * qw;
  4670. var sqz = qz * qz;
  4671. var sqx = qx * qx;
  4672. var sqy = qy * qy;
  4673. var zAxisY = qy * qz - qx * qw;
  4674. var limit = .4999999;
  4675. if (zAxisY < -limit) {
  4676. result.y = 2 * Math.atan2(qy, qw);
  4677. result.x = Math.PI / 2;
  4678. result.z = 0;
  4679. }
  4680. else if (zAxisY > limit) {
  4681. result.y = 2 * Math.atan2(qy, qw);
  4682. result.x = -Math.PI / 2;
  4683. result.z = 0;
  4684. }
  4685. else {
  4686. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4687. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4688. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4689. }
  4690. return this;
  4691. };
  4692. /**
  4693. * Updates the given rotation matrix with the current quaternion values
  4694. * @param result defines the target matrix
  4695. * @returns the current unchanged quaternion
  4696. */
  4697. Quaternion.prototype.toRotationMatrix = function (result) {
  4698. var xx = this.x * this.x;
  4699. var yy = this.y * this.y;
  4700. var zz = this.z * this.z;
  4701. var xy = this.x * this.y;
  4702. var zw = this.z * this.w;
  4703. var zx = this.z * this.x;
  4704. var yw = this.y * this.w;
  4705. var yz = this.y * this.z;
  4706. var xw = this.x * this.w;
  4707. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4708. result.m[1] = 2.0 * (xy + zw);
  4709. result.m[2] = 2.0 * (zx - yw);
  4710. result.m[3] = 0;
  4711. result.m[4] = 2.0 * (xy - zw);
  4712. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4713. result.m[6] = 2.0 * (yz + xw);
  4714. result.m[7] = 0;
  4715. result.m[8] = 2.0 * (zx + yw);
  4716. result.m[9] = 2.0 * (yz - xw);
  4717. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4718. result.m[11] = 0;
  4719. result.m[12] = 0;
  4720. result.m[13] = 0;
  4721. result.m[14] = 0;
  4722. result.m[15] = 1.0;
  4723. result._markAsUpdated();
  4724. return this;
  4725. };
  4726. /**
  4727. * Updates the current quaternion from the given rotation matrix values
  4728. * @param matrix defines the source matrix
  4729. * @returns the current updated quaternion
  4730. */
  4731. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4732. Quaternion.FromRotationMatrixToRef(matrix, this);
  4733. return this;
  4734. };
  4735. // Statics
  4736. /**
  4737. * Creates a new quaternion from a rotation matrix
  4738. * @param matrix defines the source matrix
  4739. * @returns a new quaternion created from the given rotation matrix values
  4740. */
  4741. Quaternion.FromRotationMatrix = function (matrix) {
  4742. var result = new Quaternion();
  4743. Quaternion.FromRotationMatrixToRef(matrix, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Updates the given quaternion with the given rotation matrix values
  4748. * @param matrix defines the source matrix
  4749. * @param result defines the target quaternion
  4750. */
  4751. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4752. var data = matrix.m;
  4753. var m11 = data[0], m12 = data[4], m13 = data[8];
  4754. var m21 = data[1], m22 = data[5], m23 = data[9];
  4755. var m31 = data[2], m32 = data[6], m33 = data[10];
  4756. var trace = m11 + m22 + m33;
  4757. var s;
  4758. if (trace > 0) {
  4759. s = 0.5 / Math.sqrt(trace + 1.0);
  4760. result.w = 0.25 / s;
  4761. result.x = (m32 - m23) * s;
  4762. result.y = (m13 - m31) * s;
  4763. result.z = (m21 - m12) * s;
  4764. }
  4765. else if (m11 > m22 && m11 > m33) {
  4766. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4767. result.w = (m32 - m23) / s;
  4768. result.x = 0.25 * s;
  4769. result.y = (m12 + m21) / s;
  4770. result.z = (m13 + m31) / s;
  4771. }
  4772. else if (m22 > m33) {
  4773. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4774. result.w = (m13 - m31) / s;
  4775. result.x = (m12 + m21) / s;
  4776. result.y = 0.25 * s;
  4777. result.z = (m23 + m32) / s;
  4778. }
  4779. else {
  4780. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4781. result.w = (m21 - m12) / s;
  4782. result.x = (m13 + m31) / s;
  4783. result.y = (m23 + m32) / s;
  4784. result.z = 0.25 * s;
  4785. }
  4786. };
  4787. /**
  4788. * Returns the dot product (float) between the quaternions "left" and "right"
  4789. * @param left defines the left operand
  4790. * @param right defines the right operand
  4791. * @returns the dot product
  4792. */
  4793. Quaternion.Dot = function (left, right) {
  4794. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4795. };
  4796. /**
  4797. * Checks if the two quaternions are close to each other
  4798. * @param quat0 defines the first quaternion to check
  4799. * @param quat1 defines the second quaternion to check
  4800. * @returns true if the two quaternions are close to each other
  4801. */
  4802. Quaternion.AreClose = function (quat0, quat1) {
  4803. var dot = Quaternion.Dot(quat0, quat1);
  4804. return dot >= 0;
  4805. };
  4806. /**
  4807. * Creates an empty quaternion
  4808. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4809. */
  4810. Quaternion.Zero = function () {
  4811. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4812. };
  4813. /**
  4814. * Inverse a given quaternion
  4815. * @param q defines the source quaternion
  4816. * @returns a new quaternion as the inverted current quaternion
  4817. */
  4818. Quaternion.Inverse = function (q) {
  4819. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4820. };
  4821. /**
  4822. * Creates an identity quaternion
  4823. * @returns the identity quaternion
  4824. */
  4825. Quaternion.Identity = function () {
  4826. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4827. };
  4828. /**
  4829. * Gets a boolean indicating if the given quaternion is identity
  4830. * @param quaternion defines the quaternion to check
  4831. * @returns true if the quaternion is identity
  4832. */
  4833. Quaternion.IsIdentity = function (quaternion) {
  4834. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4835. };
  4836. /**
  4837. * Creates a quaternion from a rotation around an axis
  4838. * @param axis defines the axis to use
  4839. * @param angle defines the angle to use
  4840. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4841. */
  4842. Quaternion.RotationAxis = function (axis, angle) {
  4843. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4844. };
  4845. /**
  4846. * Creates a rotation around an axis and stores it into the given quaternion
  4847. * @param axis defines the axis to use
  4848. * @param angle defines the angle to use
  4849. * @param result defines the target quaternion
  4850. * @returns the target quaternion
  4851. */
  4852. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4853. var sin = Math.sin(angle / 2);
  4854. axis.normalize();
  4855. result.w = Math.cos(angle / 2);
  4856. result.x = axis.x * sin;
  4857. result.y = axis.y * sin;
  4858. result.z = axis.z * sin;
  4859. return result;
  4860. };
  4861. /**
  4862. * Creates a new quaternion from data stored into an array
  4863. * @param array defines the data source
  4864. * @param offset defines the offset in the source array where the data starts
  4865. * @returns a new quaternion
  4866. */
  4867. Quaternion.FromArray = function (array, offset) {
  4868. if (!offset) {
  4869. offset = 0;
  4870. }
  4871. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4872. };
  4873. /**
  4874. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4875. * @param yaw defines the rotation around Y axis
  4876. * @param pitch defines the rotation around X axis
  4877. * @param roll defines the rotation around Z axis
  4878. * @returns the new quaternion
  4879. */
  4880. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4881. var q = new Quaternion();
  4882. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4883. return q;
  4884. };
  4885. /**
  4886. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4887. * @param yaw defines the rotation around Y axis
  4888. * @param pitch defines the rotation around X axis
  4889. * @param roll defines the rotation around Z axis
  4890. * @param result defines the target quaternion
  4891. */
  4892. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4893. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4894. var halfRoll = roll * 0.5;
  4895. var halfPitch = pitch * 0.5;
  4896. var halfYaw = yaw * 0.5;
  4897. var sinRoll = Math.sin(halfRoll);
  4898. var cosRoll = Math.cos(halfRoll);
  4899. var sinPitch = Math.sin(halfPitch);
  4900. var cosPitch = Math.cos(halfPitch);
  4901. var sinYaw = Math.sin(halfYaw);
  4902. var cosYaw = Math.cos(halfYaw);
  4903. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4904. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4905. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4906. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4907. };
  4908. /**
  4909. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4910. * @param alpha defines the rotation around first axis
  4911. * @param beta defines the rotation around second axis
  4912. * @param gamma defines the rotation around third axis
  4913. * @returns the new quaternion
  4914. */
  4915. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4916. var result = new Quaternion();
  4917. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4918. return result;
  4919. };
  4920. /**
  4921. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4922. * @param alpha defines the rotation around first axis
  4923. * @param beta defines the rotation around second axis
  4924. * @param gamma defines the rotation around third axis
  4925. * @param result defines the target quaternion
  4926. */
  4927. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4928. // Produces a quaternion from Euler angles in the z-x-z orientation
  4929. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4930. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4931. var halfBeta = beta * 0.5;
  4932. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4933. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4934. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4935. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4936. };
  4937. /**
  4938. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4939. * @param axis1 defines the first axis
  4940. * @param axis2 defines the second axis
  4941. * @param axis3 defines the third axis
  4942. * @returns the new quaternion
  4943. */
  4944. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4945. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4946. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4947. return quat;
  4948. };
  4949. /**
  4950. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4951. * @param axis1 defines the first axis
  4952. * @param axis2 defines the second axis
  4953. * @param axis3 defines the third axis
  4954. * @param ref defines the target quaternion
  4955. */
  4956. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4957. var rotMat = MathTmp.Matrix[0];
  4958. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4959. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4960. };
  4961. /**
  4962. * Interpolates between two quaternions
  4963. * @param left defines first quaternion
  4964. * @param right defines second quaternion
  4965. * @param amount defines the gradient to use
  4966. * @returns the new interpolated quaternion
  4967. */
  4968. Quaternion.Slerp = function (left, right, amount) {
  4969. var result = Quaternion.Identity();
  4970. Quaternion.SlerpToRef(left, right, amount, result);
  4971. return result;
  4972. };
  4973. /**
  4974. * Interpolates between two quaternions and stores it into a target quaternion
  4975. * @param left defines first quaternion
  4976. * @param right defines second quaternion
  4977. * @param amount defines the gradient to use
  4978. * @param result defines the target quaternion
  4979. */
  4980. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4981. var num2;
  4982. var num3;
  4983. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4984. var flag = false;
  4985. if (num4 < 0) {
  4986. flag = true;
  4987. num4 = -num4;
  4988. }
  4989. if (num4 > 0.999999) {
  4990. num3 = 1 - amount;
  4991. num2 = flag ? -amount : amount;
  4992. }
  4993. else {
  4994. var num5 = Math.acos(num4);
  4995. var num6 = (1.0 / Math.sin(num5));
  4996. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4997. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4998. }
  4999. result.x = (num3 * left.x) + (num2 * right.x);
  5000. result.y = (num3 * left.y) + (num2 * right.y);
  5001. result.z = (num3 * left.z) + (num2 * right.z);
  5002. result.w = (num3 * left.w) + (num2 * right.w);
  5003. };
  5004. /**
  5005. * Interpolate between two quaternions using Hermite interpolation
  5006. * @param value1 defines first quaternion
  5007. * @param tangent1 defines the incoming tangent
  5008. * @param value2 defines second quaternion
  5009. * @param tangent2 defines the outgoing tangent
  5010. * @param amount defines the target quaternion
  5011. * @returns the new interpolated quaternion
  5012. */
  5013. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5014. var squared = amount * amount;
  5015. var cubed = amount * squared;
  5016. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5017. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5018. var part3 = (cubed - (2.0 * squared)) + amount;
  5019. var part4 = cubed - squared;
  5020. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5021. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5022. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5023. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5024. return new Quaternion(x, y, z, w);
  5025. };
  5026. return Quaternion;
  5027. }());
  5028. BABYLON.Quaternion = Quaternion;
  5029. /**
  5030. * Class used to store matrix data (4x4)
  5031. */
  5032. var Matrix = /** @class */ (function () {
  5033. /**
  5034. * Creates an empty matrix (filled with zeros)
  5035. */
  5036. function Matrix() {
  5037. this._isIdentity = false;
  5038. this._isIdentityDirty = true;
  5039. /**
  5040. * Gets or sets the internal data of the matrix
  5041. */
  5042. this.m = new Float32Array(16);
  5043. this._markAsUpdated();
  5044. }
  5045. /** @hidden */
  5046. Matrix.prototype._markAsUpdated = function () {
  5047. this.updateFlag = Matrix._updateFlagSeed++;
  5048. this._isIdentityDirty = true;
  5049. };
  5050. // Properties
  5051. /**
  5052. * Check if the current matrix is indentity
  5053. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5054. * @returns true is the matrix is the identity matrix
  5055. */
  5056. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5057. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5058. if (this._isIdentityDirty) {
  5059. this._isIdentityDirty = false;
  5060. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5061. this._isIdentity = false;
  5062. }
  5063. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5064. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5065. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5066. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5067. this._isIdentity = false;
  5068. }
  5069. else {
  5070. this._isIdentity = true;
  5071. }
  5072. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5073. this._isIdentity = false;
  5074. }
  5075. }
  5076. return this._isIdentity;
  5077. };
  5078. /**
  5079. * Gets the determinant of the matrix
  5080. * @returns the matrix determinant
  5081. */
  5082. Matrix.prototype.determinant = function () {
  5083. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5084. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5085. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5086. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5087. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5088. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5089. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5090. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5091. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5092. };
  5093. // Methods
  5094. /**
  5095. * Returns the matrix as a Float32Array
  5096. * @returns the matrix underlying array
  5097. */
  5098. Matrix.prototype.toArray = function () {
  5099. return this.m;
  5100. };
  5101. /**
  5102. * Returns the matrix as a Float32Array
  5103. * @returns the matrix underlying array.
  5104. */
  5105. Matrix.prototype.asArray = function () {
  5106. return this.toArray();
  5107. };
  5108. /**
  5109. * Inverts the current matrix in place
  5110. * @returns the current inverted matrix
  5111. */
  5112. Matrix.prototype.invert = function () {
  5113. this.invertToRef(this);
  5114. return this;
  5115. };
  5116. /**
  5117. * Sets all the matrix elements to zero
  5118. * @returns the current matrix
  5119. */
  5120. Matrix.prototype.reset = function () {
  5121. for (var index = 0; index < 16; index++) {
  5122. this.m[index] = 0.0;
  5123. }
  5124. this._markAsUpdated();
  5125. return this;
  5126. };
  5127. /**
  5128. * Adds the current matrix with a second one
  5129. * @param other defines the matrix to add
  5130. * @returns a new matrix as the addition of the current matrix and the given one
  5131. */
  5132. Matrix.prototype.add = function (other) {
  5133. var result = new Matrix();
  5134. this.addToRef(other, result);
  5135. return result;
  5136. };
  5137. /**
  5138. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5139. * @param other defines the matrix to add
  5140. * @param result defines the target matrix
  5141. * @returns the current matrix
  5142. */
  5143. Matrix.prototype.addToRef = function (other, result) {
  5144. for (var index = 0; index < 16; index++) {
  5145. result.m[index] = this.m[index] + other.m[index];
  5146. }
  5147. result._markAsUpdated();
  5148. return this;
  5149. };
  5150. /**
  5151. * Adds in place the given matrix to the current matrix
  5152. * @param other defines the second operand
  5153. * @returns the current updated matrix
  5154. */
  5155. Matrix.prototype.addToSelf = function (other) {
  5156. for (var index = 0; index < 16; index++) {
  5157. this.m[index] += other.m[index];
  5158. }
  5159. this._markAsUpdated();
  5160. return this;
  5161. };
  5162. /**
  5163. * Sets the given matrix to the current inverted Matrix
  5164. * @param other defines the target matrix
  5165. * @returns the unmodified current matrix
  5166. */
  5167. Matrix.prototype.invertToRef = function (other) {
  5168. var l1 = this.m[0];
  5169. var l2 = this.m[1];
  5170. var l3 = this.m[2];
  5171. var l4 = this.m[3];
  5172. var l5 = this.m[4];
  5173. var l6 = this.m[5];
  5174. var l7 = this.m[6];
  5175. var l8 = this.m[7];
  5176. var l9 = this.m[8];
  5177. var l10 = this.m[9];
  5178. var l11 = this.m[10];
  5179. var l12 = this.m[11];
  5180. var l13 = this.m[12];
  5181. var l14 = this.m[13];
  5182. var l15 = this.m[14];
  5183. var l16 = this.m[15];
  5184. var l17 = (l11 * l16) - (l12 * l15);
  5185. var l18 = (l10 * l16) - (l12 * l14);
  5186. var l19 = (l10 * l15) - (l11 * l14);
  5187. var l20 = (l9 * l16) - (l12 * l13);
  5188. var l21 = (l9 * l15) - (l11 * l13);
  5189. var l22 = (l9 * l14) - (l10 * l13);
  5190. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5191. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5192. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5193. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5194. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5195. var l28 = (l7 * l16) - (l8 * l15);
  5196. var l29 = (l6 * l16) - (l8 * l14);
  5197. var l30 = (l6 * l15) - (l7 * l14);
  5198. var l31 = (l5 * l16) - (l8 * l13);
  5199. var l32 = (l5 * l15) - (l7 * l13);
  5200. var l33 = (l5 * l14) - (l6 * l13);
  5201. var l34 = (l7 * l12) - (l8 * l11);
  5202. var l35 = (l6 * l12) - (l8 * l10);
  5203. var l36 = (l6 * l11) - (l7 * l10);
  5204. var l37 = (l5 * l12) - (l8 * l9);
  5205. var l38 = (l5 * l11) - (l7 * l9);
  5206. var l39 = (l5 * l10) - (l6 * l9);
  5207. other.m[0] = l23 * l27;
  5208. other.m[4] = l24 * l27;
  5209. other.m[8] = l25 * l27;
  5210. other.m[12] = l26 * l27;
  5211. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5212. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5213. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5214. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5215. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5216. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5217. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5218. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5219. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5220. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5221. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5222. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5223. other._markAsUpdated();
  5224. return this;
  5225. };
  5226. /**
  5227. * Inserts the translation vector (using 3 floats) in the current matrix
  5228. * @param x defines the 1st component of the translation
  5229. * @param y defines the 2nd component of the translation
  5230. * @param z defines the 3rd component of the translation
  5231. * @returns the current updated matrix
  5232. */
  5233. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5234. this.m[12] = x;
  5235. this.m[13] = y;
  5236. this.m[14] = z;
  5237. this._markAsUpdated();
  5238. return this;
  5239. };
  5240. /**
  5241. * Inserts the translation vector in the current matrix
  5242. * @param vector3 defines the translation to insert
  5243. * @returns the current updated matrix
  5244. */
  5245. Matrix.prototype.setTranslation = function (vector3) {
  5246. this.m[12] = vector3.x;
  5247. this.m[13] = vector3.y;
  5248. this.m[14] = vector3.z;
  5249. this._markAsUpdated();
  5250. return this;
  5251. };
  5252. /**
  5253. * Gets the translation value of the current matrix
  5254. * @returns a new Vector3 as the extracted translation from the matrix
  5255. */
  5256. Matrix.prototype.getTranslation = function () {
  5257. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5258. };
  5259. /**
  5260. * Fill a Vector3 with the extracted translation from the matrix
  5261. * @param result defines the Vector3 where to store the translation
  5262. * @returns the current matrix
  5263. */
  5264. Matrix.prototype.getTranslationToRef = function (result) {
  5265. result.x = this.m[12];
  5266. result.y = this.m[13];
  5267. result.z = this.m[14];
  5268. return this;
  5269. };
  5270. /**
  5271. * Remove rotation and scaling part from the matrix
  5272. * @returns the updated matrix
  5273. */
  5274. Matrix.prototype.removeRotationAndScaling = function () {
  5275. this.setRowFromFloats(0, 1, 0, 0, 0);
  5276. this.setRowFromFloats(1, 0, 1, 0, 0);
  5277. this.setRowFromFloats(2, 0, 0, 1, 0);
  5278. return this;
  5279. };
  5280. /**
  5281. * Multiply two matrices
  5282. * @param other defines the second operand
  5283. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5284. */
  5285. Matrix.prototype.multiply = function (other) {
  5286. var result = new Matrix();
  5287. this.multiplyToRef(other, result);
  5288. return result;
  5289. };
  5290. /**
  5291. * Copy the current matrix from the given one
  5292. * @param other defines the source matrix
  5293. * @returns the current updated matrix
  5294. */
  5295. Matrix.prototype.copyFrom = function (other) {
  5296. for (var index = 0; index < 16; index++) {
  5297. this.m[index] = other.m[index];
  5298. }
  5299. this._markAsUpdated();
  5300. return this;
  5301. };
  5302. /**
  5303. * Populates the given array from the starting index with the current matrix values
  5304. * @param array defines the target array
  5305. * @param offset defines the offset in the target array where to start storing values
  5306. * @returns the current matrix
  5307. */
  5308. Matrix.prototype.copyToArray = function (array, offset) {
  5309. if (offset === void 0) { offset = 0; }
  5310. for (var index = 0; index < 16; index++) {
  5311. array[offset + index] = this.m[index];
  5312. }
  5313. return this;
  5314. };
  5315. /**
  5316. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5317. * @param other defines the second operand
  5318. * @param result defines the matrix where to store the multiplication
  5319. * @returns the current matrix
  5320. */
  5321. Matrix.prototype.multiplyToRef = function (other, result) {
  5322. this.multiplyToArray(other, result.m, 0);
  5323. result._markAsUpdated();
  5324. return this;
  5325. };
  5326. /**
  5327. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5328. * @param other defines the second operand
  5329. * @param result defines the array where to store the multiplication
  5330. * @param offset defines the offset in the target array where to start storing values
  5331. * @returns the current matrix
  5332. */
  5333. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5334. var tm0 = this.m[0];
  5335. var tm1 = this.m[1];
  5336. var tm2 = this.m[2];
  5337. var tm3 = this.m[3];
  5338. var tm4 = this.m[4];
  5339. var tm5 = this.m[5];
  5340. var tm6 = this.m[6];
  5341. var tm7 = this.m[7];
  5342. var tm8 = this.m[8];
  5343. var tm9 = this.m[9];
  5344. var tm10 = this.m[10];
  5345. var tm11 = this.m[11];
  5346. var tm12 = this.m[12];
  5347. var tm13 = this.m[13];
  5348. var tm14 = this.m[14];
  5349. var tm15 = this.m[15];
  5350. var om0 = other.m[0];
  5351. var om1 = other.m[1];
  5352. var om2 = other.m[2];
  5353. var om3 = other.m[3];
  5354. var om4 = other.m[4];
  5355. var om5 = other.m[5];
  5356. var om6 = other.m[6];
  5357. var om7 = other.m[7];
  5358. var om8 = other.m[8];
  5359. var om9 = other.m[9];
  5360. var om10 = other.m[10];
  5361. var om11 = other.m[11];
  5362. var om12 = other.m[12];
  5363. var om13 = other.m[13];
  5364. var om14 = other.m[14];
  5365. var om15 = other.m[15];
  5366. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5367. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5368. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5369. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5370. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5371. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5372. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5373. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5374. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5375. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5376. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5377. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5378. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5379. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5380. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5381. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5382. return this;
  5383. };
  5384. /**
  5385. * Check equality between this matrix and a second one
  5386. * @param value defines the second matrix to compare
  5387. * @returns true is the current matrix and the given one values are strictly equal
  5388. */
  5389. Matrix.prototype.equals = function (value) {
  5390. return value &&
  5391. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5392. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5393. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5394. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5395. };
  5396. /**
  5397. * Clone the current matrix
  5398. * @returns a new matrix from the current matrix
  5399. */
  5400. Matrix.prototype.clone = function () {
  5401. 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]);
  5402. };
  5403. /**
  5404. * Returns the name of the current matrix class
  5405. * @returns the string "Matrix"
  5406. */
  5407. Matrix.prototype.getClassName = function () {
  5408. return "Matrix";
  5409. };
  5410. /**
  5411. * Gets the hash code of the current matrix
  5412. * @returns the hash code
  5413. */
  5414. Matrix.prototype.getHashCode = function () {
  5415. var hash = this.m[0] || 0;
  5416. for (var i = 1; i < 16; i++) {
  5417. hash = (hash * 397) ^ (this.m[i] || 0);
  5418. }
  5419. return hash;
  5420. };
  5421. /**
  5422. * Decomposes the current Matrix into a translation, rotation and scaling components
  5423. * @param scale defines the scale vector3 given as a reference to update
  5424. * @param rotation defines the rotation quaternion given as a reference to update
  5425. * @param translation defines the translation vector3 given as a reference to update
  5426. * @returns true if operation was successful
  5427. */
  5428. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5429. if (translation) {
  5430. translation.x = this.m[12];
  5431. translation.y = this.m[13];
  5432. translation.z = this.m[14];
  5433. }
  5434. scale = scale || MathTmp.Vector3[0];
  5435. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5436. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5437. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5438. if (this.determinant() <= 0) {
  5439. scale.y *= -1;
  5440. }
  5441. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5442. if (rotation) {
  5443. rotation.x = 0;
  5444. rotation.y = 0;
  5445. rotation.z = 0;
  5446. rotation.w = 1;
  5447. }
  5448. return false;
  5449. }
  5450. if (rotation) {
  5451. 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]);
  5452. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5453. }
  5454. return true;
  5455. };
  5456. /**
  5457. * Gets specific row of the matrix
  5458. * @param index defines the number of the row to get
  5459. * @returns the index-th row of the current matrix as a new Vector4
  5460. */
  5461. Matrix.prototype.getRow = function (index) {
  5462. if (index < 0 || index > 3) {
  5463. return null;
  5464. }
  5465. var i = index * 4;
  5466. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5467. };
  5468. /**
  5469. * Sets the index-th row of the current matrix to the vector4 values
  5470. * @param index defines the number of the row to set
  5471. * @param row defines the target vector4
  5472. * @returns the updated current matrix
  5473. */
  5474. Matrix.prototype.setRow = function (index, row) {
  5475. if (index < 0 || index > 3) {
  5476. return this;
  5477. }
  5478. var i = index * 4;
  5479. this.m[i + 0] = row.x;
  5480. this.m[i + 1] = row.y;
  5481. this.m[i + 2] = row.z;
  5482. this.m[i + 3] = row.w;
  5483. this._markAsUpdated();
  5484. return this;
  5485. };
  5486. /**
  5487. * Compute the transpose of the matrix
  5488. * @returns the new transposed matrix
  5489. */
  5490. Matrix.prototype.transpose = function () {
  5491. return Matrix.Transpose(this);
  5492. };
  5493. /**
  5494. * Compute the transpose of the matrix and store it in a given matrix
  5495. * @param result defines the target matrix
  5496. * @returns the current matrix
  5497. */
  5498. Matrix.prototype.transposeToRef = function (result) {
  5499. Matrix.TransposeToRef(this, result);
  5500. return this;
  5501. };
  5502. /**
  5503. * Sets the index-th row of the current matrix with the given 4 x float values
  5504. * @param index defines the row index
  5505. * @param x defines the x component to set
  5506. * @param y defines the y component to set
  5507. * @param z defines the z component to set
  5508. * @param w defines the w component to set
  5509. * @returns the updated current matrix
  5510. */
  5511. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5512. if (index < 0 || index > 3) {
  5513. return this;
  5514. }
  5515. var i = index * 4;
  5516. this.m[i + 0] = x;
  5517. this.m[i + 1] = y;
  5518. this.m[i + 2] = z;
  5519. this.m[i + 3] = w;
  5520. this._markAsUpdated();
  5521. return this;
  5522. };
  5523. /**
  5524. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5525. * @param scale defines the scale factor
  5526. * @returns a new matrix
  5527. */
  5528. Matrix.prototype.scale = function (scale) {
  5529. var result = new Matrix();
  5530. this.scaleToRef(scale, result);
  5531. return result;
  5532. };
  5533. /**
  5534. * Scale the current matrix values by a factor to a given result matrix
  5535. * @param scale defines the scale factor
  5536. * @param result defines the matrix to store the result
  5537. * @returns the current matrix
  5538. */
  5539. Matrix.prototype.scaleToRef = function (scale, result) {
  5540. for (var index = 0; index < 16; index++) {
  5541. result.m[index] = this.m[index] * scale;
  5542. }
  5543. result._markAsUpdated();
  5544. return this;
  5545. };
  5546. /**
  5547. * Scale the current matrix values by a factor and add the result to a given matrix
  5548. * @param scale defines the scale factor
  5549. * @param result defines the Matrix to store the result
  5550. * @returns the current matrix
  5551. */
  5552. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5553. for (var index = 0; index < 16; index++) {
  5554. result.m[index] += this.m[index] * scale;
  5555. }
  5556. result._markAsUpdated();
  5557. return this;
  5558. };
  5559. /**
  5560. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5561. * @param ref matrix to store the result
  5562. */
  5563. Matrix.prototype.toNormalMatrix = function (ref) {
  5564. this.invertToRef(ref);
  5565. ref.transpose();
  5566. var m = ref.m;
  5567. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5568. };
  5569. /**
  5570. * Gets only rotation part of the current matrix
  5571. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5572. */
  5573. Matrix.prototype.getRotationMatrix = function () {
  5574. var result = Matrix.Identity();
  5575. this.getRotationMatrixToRef(result);
  5576. return result;
  5577. };
  5578. /**
  5579. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5580. * @param result defines the target matrix to store data to
  5581. * @returns the current matrix
  5582. */
  5583. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5584. var m = this.m;
  5585. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5586. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5587. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5588. if (this.determinant() <= 0) {
  5589. sy *= -1;
  5590. }
  5591. if (sx === 0 || sy === 0 || sz === 0) {
  5592. Matrix.IdentityToRef(result);
  5593. }
  5594. else {
  5595. 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);
  5596. }
  5597. return this;
  5598. };
  5599. // Statics
  5600. /**
  5601. * Creates a matrix from an array
  5602. * @param array defines the source array
  5603. * @param offset defines an offset in the source array
  5604. * @returns a new Matrix set from the starting index of the given array
  5605. */
  5606. Matrix.FromArray = function (array, offset) {
  5607. var result = new Matrix();
  5608. if (!offset) {
  5609. offset = 0;
  5610. }
  5611. Matrix.FromArrayToRef(array, offset, result);
  5612. return result;
  5613. };
  5614. /**
  5615. * Copy the content of an array into a given matrix
  5616. * @param array defines the source array
  5617. * @param offset defines an offset in the source array
  5618. * @param result defines the target matrix
  5619. */
  5620. Matrix.FromArrayToRef = function (array, offset, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] = array[index + offset];
  5623. }
  5624. result._markAsUpdated();
  5625. };
  5626. /**
  5627. * Stores an array into a matrix after having multiplied each component by a given factor
  5628. * @param array defines the source array
  5629. * @param offset defines the offset in the source array
  5630. * @param scale defines the scaling factor
  5631. * @param result defines the target matrix
  5632. */
  5633. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5634. for (var index = 0; index < 16; index++) {
  5635. result.m[index] = array[index + offset] * scale;
  5636. }
  5637. result._markAsUpdated();
  5638. };
  5639. /**
  5640. * Stores a list of values (16) inside a given matrix
  5641. * @param initialM11 defines 1st value of 1st row
  5642. * @param initialM12 defines 2nd value of 1st row
  5643. * @param initialM13 defines 3rd value of 1st row
  5644. * @param initialM14 defines 4th value of 1st row
  5645. * @param initialM21 defines 1st value of 2nd row
  5646. * @param initialM22 defines 2nd value of 2nd row
  5647. * @param initialM23 defines 3rd value of 2nd row
  5648. * @param initialM24 defines 4th value of 2nd row
  5649. * @param initialM31 defines 1st value of 3rd row
  5650. * @param initialM32 defines 2nd value of 3rd row
  5651. * @param initialM33 defines 3rd value of 3rd row
  5652. * @param initialM34 defines 4th value of 3rd row
  5653. * @param initialM41 defines 1st value of 4th row
  5654. * @param initialM42 defines 2nd value of 4th row
  5655. * @param initialM43 defines 3rd value of 4th row
  5656. * @param initialM44 defines 4th value of 4th row
  5657. * @param result defines the target matrix
  5658. */
  5659. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5660. result.m[0] = initialM11;
  5661. result.m[1] = initialM12;
  5662. result.m[2] = initialM13;
  5663. result.m[3] = initialM14;
  5664. result.m[4] = initialM21;
  5665. result.m[5] = initialM22;
  5666. result.m[6] = initialM23;
  5667. result.m[7] = initialM24;
  5668. result.m[8] = initialM31;
  5669. result.m[9] = initialM32;
  5670. result.m[10] = initialM33;
  5671. result.m[11] = initialM34;
  5672. result.m[12] = initialM41;
  5673. result.m[13] = initialM42;
  5674. result.m[14] = initialM43;
  5675. result.m[15] = initialM44;
  5676. result._markAsUpdated();
  5677. };
  5678. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5679. /**
  5680. * Gets an identity matrix that must not be updated
  5681. */
  5682. get: function () {
  5683. return Matrix._identityReadOnly;
  5684. },
  5685. enumerable: true,
  5686. configurable: true
  5687. });
  5688. /**
  5689. * Creates new matrix from a list of values (16)
  5690. * @param initialM11 defines 1st value of 1st row
  5691. * @param initialM12 defines 2nd value of 1st row
  5692. * @param initialM13 defines 3rd value of 1st row
  5693. * @param initialM14 defines 4th value of 1st row
  5694. * @param initialM21 defines 1st value of 2nd row
  5695. * @param initialM22 defines 2nd value of 2nd row
  5696. * @param initialM23 defines 3rd value of 2nd row
  5697. * @param initialM24 defines 4th value of 2nd row
  5698. * @param initialM31 defines 1st value of 3rd row
  5699. * @param initialM32 defines 2nd value of 3rd row
  5700. * @param initialM33 defines 3rd value of 3rd row
  5701. * @param initialM34 defines 4th value of 3rd row
  5702. * @param initialM41 defines 1st value of 4th row
  5703. * @param initialM42 defines 2nd value of 4th row
  5704. * @param initialM43 defines 3rd value of 4th row
  5705. * @param initialM44 defines 4th value of 4th row
  5706. * @returns the new matrix
  5707. */
  5708. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5709. var result = new Matrix();
  5710. result.m[0] = initialM11;
  5711. result.m[1] = initialM12;
  5712. result.m[2] = initialM13;
  5713. result.m[3] = initialM14;
  5714. result.m[4] = initialM21;
  5715. result.m[5] = initialM22;
  5716. result.m[6] = initialM23;
  5717. result.m[7] = initialM24;
  5718. result.m[8] = initialM31;
  5719. result.m[9] = initialM32;
  5720. result.m[10] = initialM33;
  5721. result.m[11] = initialM34;
  5722. result.m[12] = initialM41;
  5723. result.m[13] = initialM42;
  5724. result.m[14] = initialM43;
  5725. result.m[15] = initialM44;
  5726. return result;
  5727. };
  5728. /**
  5729. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5730. * @param scale defines the scale vector3
  5731. * @param rotation defines the rotation quaternion
  5732. * @param translation defines the translation vector3
  5733. * @returns a new matrix
  5734. */
  5735. Matrix.Compose = function (scale, rotation, translation) {
  5736. var result = Matrix.Identity();
  5737. Matrix.ComposeToRef(scale, rotation, translation, result);
  5738. return result;
  5739. };
  5740. /**
  5741. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5742. * @param scale defines the scale vector3
  5743. * @param rotation defines the rotation quaternion
  5744. * @param translation defines the translation vector3
  5745. * @param result defines the target matrix
  5746. */
  5747. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5748. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5749. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5750. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5751. result.setTranslation(translation);
  5752. };
  5753. /**
  5754. * Creates a new identity matrix
  5755. * @returns a new identity matrix
  5756. */
  5757. Matrix.Identity = function () {
  5758. 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);
  5759. };
  5760. /**
  5761. * Creates a new identity matrix and stores the result in a given matrix
  5762. * @param result defines the target matrix
  5763. */
  5764. Matrix.IdentityToRef = function (result) {
  5765. 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);
  5766. };
  5767. /**
  5768. * Creates a new zero matrix
  5769. * @returns a new zero matrix
  5770. */
  5771. Matrix.Zero = function () {
  5772. 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);
  5773. };
  5774. /**
  5775. * Creates a new rotation matrix for "angle" radians around the X axis
  5776. * @param angle defines the angle (in radians) to use
  5777. * @return the new matrix
  5778. */
  5779. Matrix.RotationX = function (angle) {
  5780. var result = new Matrix();
  5781. Matrix.RotationXToRef(angle, result);
  5782. return result;
  5783. };
  5784. /**
  5785. * Creates a new matrix as the invert of a given matrix
  5786. * @param source defines the source matrix
  5787. * @returns the new matrix
  5788. */
  5789. Matrix.Invert = function (source) {
  5790. var result = new Matrix();
  5791. source.invertToRef(result);
  5792. return result;
  5793. };
  5794. /**
  5795. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5796. * @param angle defines the angle (in radians) to use
  5797. * @param result defines the target matrix
  5798. */
  5799. Matrix.RotationXToRef = function (angle, result) {
  5800. var s = Math.sin(angle);
  5801. var c = Math.cos(angle);
  5802. result.m[0] = 1.0;
  5803. result.m[15] = 1.0;
  5804. result.m[5] = c;
  5805. result.m[10] = c;
  5806. result.m[9] = -s;
  5807. result.m[6] = s;
  5808. result.m[1] = 0.0;
  5809. result.m[2] = 0.0;
  5810. result.m[3] = 0.0;
  5811. result.m[4] = 0.0;
  5812. result.m[7] = 0.0;
  5813. result.m[8] = 0.0;
  5814. result.m[11] = 0.0;
  5815. result.m[12] = 0.0;
  5816. result.m[13] = 0.0;
  5817. result.m[14] = 0.0;
  5818. result._markAsUpdated();
  5819. };
  5820. /**
  5821. * Creates a new rotation matrix for "angle" radians around the Y axis
  5822. * @param angle defines the angle (in radians) to use
  5823. * @return the new matrix
  5824. */
  5825. Matrix.RotationY = function (angle) {
  5826. var result = new Matrix();
  5827. Matrix.RotationYToRef(angle, result);
  5828. return result;
  5829. };
  5830. /**
  5831. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5832. * @param angle defines the angle (in radians) to use
  5833. * @param result defines the target matrix
  5834. */
  5835. Matrix.RotationYToRef = function (angle, result) {
  5836. var s = Math.sin(angle);
  5837. var c = Math.cos(angle);
  5838. result.m[5] = 1.0;
  5839. result.m[15] = 1.0;
  5840. result.m[0] = c;
  5841. result.m[2] = -s;
  5842. result.m[8] = s;
  5843. result.m[10] = c;
  5844. result.m[1] = 0.0;
  5845. result.m[3] = 0.0;
  5846. result.m[4] = 0.0;
  5847. result.m[6] = 0.0;
  5848. result.m[7] = 0.0;
  5849. result.m[9] = 0.0;
  5850. result.m[11] = 0.0;
  5851. result.m[12] = 0.0;
  5852. result.m[13] = 0.0;
  5853. result.m[14] = 0.0;
  5854. result._markAsUpdated();
  5855. };
  5856. /**
  5857. * Creates a new rotation matrix for "angle" radians around the Z axis
  5858. * @param angle defines the angle (in radians) to use
  5859. * @return the new matrix
  5860. */
  5861. Matrix.RotationZ = function (angle) {
  5862. var result = new Matrix();
  5863. Matrix.RotationZToRef(angle, result);
  5864. return result;
  5865. };
  5866. /**
  5867. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5868. * @param angle defines the angle (in radians) to use
  5869. * @param result defines the target matrix
  5870. */
  5871. Matrix.RotationZToRef = function (angle, result) {
  5872. var s = Math.sin(angle);
  5873. var c = Math.cos(angle);
  5874. result.m[10] = 1.0;
  5875. result.m[15] = 1.0;
  5876. result.m[0] = c;
  5877. result.m[1] = s;
  5878. result.m[4] = -s;
  5879. result.m[5] = c;
  5880. result.m[2] = 0.0;
  5881. result.m[3] = 0.0;
  5882. result.m[6] = 0.0;
  5883. result.m[7] = 0.0;
  5884. result.m[8] = 0.0;
  5885. result.m[9] = 0.0;
  5886. result.m[11] = 0.0;
  5887. result.m[12] = 0.0;
  5888. result.m[13] = 0.0;
  5889. result.m[14] = 0.0;
  5890. result._markAsUpdated();
  5891. };
  5892. /**
  5893. * Creates a new rotation matrix for "angle" radians around the given axis
  5894. * @param axis defines the axis to use
  5895. * @param angle defines the angle (in radians) to use
  5896. * @return the new matrix
  5897. */
  5898. Matrix.RotationAxis = function (axis, angle) {
  5899. var result = Matrix.Zero();
  5900. Matrix.RotationAxisToRef(axis, angle, result);
  5901. return result;
  5902. };
  5903. /**
  5904. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5905. * @param axis defines the axis to use
  5906. * @param angle defines the angle (in radians) to use
  5907. * @param result defines the target matrix
  5908. */
  5909. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5910. var s = Math.sin(-angle);
  5911. var c = Math.cos(-angle);
  5912. var c1 = 1 - c;
  5913. axis.normalize();
  5914. result.m[0] = (axis.x * axis.x) * c1 + c;
  5915. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5916. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5917. result.m[3] = 0.0;
  5918. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5919. result.m[5] = (axis.y * axis.y) * c1 + c;
  5920. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5921. result.m[7] = 0.0;
  5922. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5923. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5924. result.m[10] = (axis.z * axis.z) * c1 + c;
  5925. result.m[11] = 0.0;
  5926. result.m[15] = 1.0;
  5927. result._markAsUpdated();
  5928. };
  5929. /**
  5930. * Creates a rotation matrix
  5931. * @param yaw defines the yaw angle in radians (Y axis)
  5932. * @param pitch defines the pitch angle in radians (X axis)
  5933. * @param roll defines the roll angle in radians (X axis)
  5934. * @returns the new rotation matrix
  5935. */
  5936. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5937. var result = new Matrix();
  5938. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5939. return result;
  5940. };
  5941. /**
  5942. * Creates a rotation matrix and stores it in a given matrix
  5943. * @param yaw defines the yaw angle in radians (Y axis)
  5944. * @param pitch defines the pitch angle in radians (X axis)
  5945. * @param roll defines the roll angle in radians (X axis)
  5946. * @param result defines the target matrix
  5947. */
  5948. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5949. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5950. this._tempQuaternion.toRotationMatrix(result);
  5951. };
  5952. /**
  5953. * Creates a scaling matrix
  5954. * @param x defines the scale factor on X axis
  5955. * @param y defines the scale factor on Y axis
  5956. * @param z defines the scale factor on Z axis
  5957. * @returns the new matrix
  5958. */
  5959. Matrix.Scaling = function (x, y, z) {
  5960. var result = Matrix.Zero();
  5961. Matrix.ScalingToRef(x, y, z, result);
  5962. return result;
  5963. };
  5964. /**
  5965. * Creates a scaling matrix and stores it in a given matrix
  5966. * @param x defines the scale factor on X axis
  5967. * @param y defines the scale factor on Y axis
  5968. * @param z defines the scale factor on Z axis
  5969. * @param result defines the target matrix
  5970. */
  5971. Matrix.ScalingToRef = function (x, y, z, result) {
  5972. result.m[0] = x;
  5973. result.m[1] = 0.0;
  5974. result.m[2] = 0.0;
  5975. result.m[3] = 0.0;
  5976. result.m[4] = 0.0;
  5977. result.m[5] = y;
  5978. result.m[6] = 0.0;
  5979. result.m[7] = 0.0;
  5980. result.m[8] = 0.0;
  5981. result.m[9] = 0.0;
  5982. result.m[10] = z;
  5983. result.m[11] = 0.0;
  5984. result.m[12] = 0.0;
  5985. result.m[13] = 0.0;
  5986. result.m[14] = 0.0;
  5987. result.m[15] = 1.0;
  5988. result._markAsUpdated();
  5989. };
  5990. /**
  5991. * Creates a translation matrix
  5992. * @param x defines the translation on X axis
  5993. * @param y defines the translation on Y axis
  5994. * @param z defines the translationon Z axis
  5995. * @returns the new matrix
  5996. */
  5997. Matrix.Translation = function (x, y, z) {
  5998. var result = Matrix.Identity();
  5999. Matrix.TranslationToRef(x, y, z, result);
  6000. return result;
  6001. };
  6002. /**
  6003. * Creates a translation matrix and stores it in a given matrix
  6004. * @param x defines the translation on X axis
  6005. * @param y defines the translation on Y axis
  6006. * @param z defines the translationon Z axis
  6007. * @param result defines the target matrix
  6008. */
  6009. Matrix.TranslationToRef = function (x, y, z, result) {
  6010. 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);
  6011. };
  6012. /**
  6013. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6014. * @param startValue defines the start value
  6015. * @param endValue defines the end value
  6016. * @param gradient defines the gradient factor
  6017. * @returns the new matrix
  6018. */
  6019. Matrix.Lerp = function (startValue, endValue, gradient) {
  6020. var result = Matrix.Zero();
  6021. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6022. return result;
  6023. };
  6024. /**
  6025. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6026. * @param startValue defines the start value
  6027. * @param endValue defines the end value
  6028. * @param gradient defines the gradient factor
  6029. * @param result defines the Matrix object where to store data
  6030. */
  6031. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6032. for (var index = 0; index < 16; index++) {
  6033. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6034. }
  6035. result._markAsUpdated();
  6036. };
  6037. /**
  6038. * Builds a new matrix whose values are computed by:
  6039. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6040. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6041. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6042. * @param startValue defines the first matrix
  6043. * @param endValue defines the second matrix
  6044. * @param gradient defines the gradient between the two matrices
  6045. * @returns the new matrix
  6046. */
  6047. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6048. var result = Matrix.Zero();
  6049. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6050. return result;
  6051. };
  6052. /**
  6053. * Update a matrix to values which are computed by:
  6054. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6055. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6056. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6057. * @param startValue defines the first matrix
  6058. * @param endValue defines the second matrix
  6059. * @param gradient defines the gradient between the two matrices
  6060. * @param result defines the target matrix
  6061. */
  6062. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6063. var startScale = MathTmp.Vector3[0];
  6064. var startRotation = MathTmp.Quaternion[0];
  6065. var startTranslation = MathTmp.Vector3[1];
  6066. startValue.decompose(startScale, startRotation, startTranslation);
  6067. var endScale = MathTmp.Vector3[2];
  6068. var endRotation = MathTmp.Quaternion[1];
  6069. var endTranslation = MathTmp.Vector3[3];
  6070. endValue.decompose(endScale, endRotation, endTranslation);
  6071. var resultScale = MathTmp.Vector3[4];
  6072. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6073. var resultRotation = MathTmp.Quaternion[2];
  6074. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6075. var resultTranslation = MathTmp.Vector3[5];
  6076. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6077. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6078. };
  6079. /**
  6080. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6081. * This function works in left handed mode
  6082. * @param eye defines the final position of the entity
  6083. * @param target defines where the entity should look at
  6084. * @param up defines the up vector for the entity
  6085. * @returns the new matrix
  6086. */
  6087. Matrix.LookAtLH = function (eye, target, up) {
  6088. var result = Matrix.Zero();
  6089. Matrix.LookAtLHToRef(eye, target, up, result);
  6090. return result;
  6091. };
  6092. /**
  6093. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6094. * This function works in left handed mode
  6095. * @param eye defines the final position of the entity
  6096. * @param target defines where the entity should look at
  6097. * @param up defines the up vector for the entity
  6098. * @param result defines the target matrix
  6099. */
  6100. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6101. // Z axis
  6102. target.subtractToRef(eye, this._zAxis);
  6103. this._zAxis.normalize();
  6104. // X axis
  6105. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6106. if (this._xAxis.lengthSquared() === 0) {
  6107. this._xAxis.x = 1.0;
  6108. }
  6109. else {
  6110. this._xAxis.normalize();
  6111. }
  6112. // Y axis
  6113. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6114. this._yAxis.normalize();
  6115. // Eye angles
  6116. var ex = -Vector3.Dot(this._xAxis, eye);
  6117. var ey = -Vector3.Dot(this._yAxis, eye);
  6118. var ez = -Vector3.Dot(this._zAxis, eye);
  6119. 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);
  6120. };
  6121. /**
  6122. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6123. * This function works in right handed mode
  6124. * @param eye defines the final position of the entity
  6125. * @param target defines where the entity should look at
  6126. * @param up defines the up vector for the entity
  6127. * @returns the new matrix
  6128. */
  6129. Matrix.LookAtRH = function (eye, target, up) {
  6130. var result = Matrix.Zero();
  6131. Matrix.LookAtRHToRef(eye, target, up, result);
  6132. return result;
  6133. };
  6134. /**
  6135. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6136. * This function works in right handed mode
  6137. * @param eye defines the final position of the entity
  6138. * @param target defines where the entity should look at
  6139. * @param up defines the up vector for the entity
  6140. * @param result defines the target matrix
  6141. */
  6142. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6143. // Z axis
  6144. eye.subtractToRef(target, this._zAxis);
  6145. this._zAxis.normalize();
  6146. // X axis
  6147. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6148. if (this._xAxis.lengthSquared() === 0) {
  6149. this._xAxis.x = 1.0;
  6150. }
  6151. else {
  6152. this._xAxis.normalize();
  6153. }
  6154. // Y axis
  6155. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6156. this._yAxis.normalize();
  6157. // Eye angles
  6158. var ex = -Vector3.Dot(this._xAxis, eye);
  6159. var ey = -Vector3.Dot(this._yAxis, eye);
  6160. var ez = -Vector3.Dot(this._zAxis, eye);
  6161. 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);
  6162. };
  6163. /**
  6164. * Create a left-handed orthographic projection matrix
  6165. * @param width defines the viewport width
  6166. * @param height defines the viewport height
  6167. * @param znear defines the near clip plane
  6168. * @param zfar defines the far clip plane
  6169. * @returns a new matrix as a left-handed orthographic projection matrix
  6170. */
  6171. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6172. var matrix = Matrix.Zero();
  6173. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6174. return matrix;
  6175. };
  6176. /**
  6177. * Store a left-handed orthographic projection to a given matrix
  6178. * @param width defines the viewport width
  6179. * @param height defines the viewport height
  6180. * @param znear defines the near clip plane
  6181. * @param zfar defines the far clip plane
  6182. * @param result defines the target matrix
  6183. */
  6184. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6185. var n = znear;
  6186. var f = zfar;
  6187. var a = 2.0 / width;
  6188. var b = 2.0 / height;
  6189. var c = 2.0 / (f - n);
  6190. var d = -(f + n) / (f - n);
  6191. 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);
  6192. };
  6193. /**
  6194. * Create a left-handed orthographic projection matrix
  6195. * @param left defines the viewport left coordinate
  6196. * @param right defines the viewport right coordinate
  6197. * @param bottom defines the viewport bottom coordinate
  6198. * @param top defines the viewport top coordinate
  6199. * @param znear defines the near clip plane
  6200. * @param zfar defines the far clip plane
  6201. * @returns a new matrix as a left-handed orthographic projection matrix
  6202. */
  6203. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6204. var matrix = Matrix.Zero();
  6205. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6206. return matrix;
  6207. };
  6208. /**
  6209. * Stores a left-handed orthographic projection into a given matrix
  6210. * @param left defines the viewport left coordinate
  6211. * @param right defines the viewport right coordinate
  6212. * @param bottom defines the viewport bottom coordinate
  6213. * @param top defines the viewport top coordinate
  6214. * @param znear defines the near clip plane
  6215. * @param zfar defines the far clip plane
  6216. * @param result defines the target matrix
  6217. */
  6218. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6219. var n = znear;
  6220. var f = zfar;
  6221. var a = 2.0 / (right - left);
  6222. var b = 2.0 / (top - bottom);
  6223. var c = 2.0 / (f - n);
  6224. var d = -(f + n) / (f - n);
  6225. var i0 = (left + right) / (left - right);
  6226. var i1 = (top + bottom) / (bottom - top);
  6227. 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);
  6228. };
  6229. /**
  6230. * Creates a right-handed orthographic projection matrix
  6231. * @param left defines the viewport left coordinate
  6232. * @param right defines the viewport right coordinate
  6233. * @param bottom defines the viewport bottom coordinate
  6234. * @param top defines the viewport top coordinate
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a right-handed orthographic projection matrix
  6238. */
  6239. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6242. return matrix;
  6243. };
  6244. /**
  6245. * Stores a right-handed orthographic projection into a given matrix
  6246. * @param left defines the viewport left coordinate
  6247. * @param right defines the viewport right coordinate
  6248. * @param bottom defines the viewport bottom coordinate
  6249. * @param top defines the viewport top coordinate
  6250. * @param znear defines the near clip plane
  6251. * @param zfar defines the far clip plane
  6252. * @param result defines the target matrix
  6253. */
  6254. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6255. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6256. result.m[10] *= -1.0;
  6257. };
  6258. /**
  6259. * Creates a left-handed perspective projection matrix
  6260. * @param width defines the viewport width
  6261. * @param height defines the viewport height
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @returns a new matrix as a left-handed perspective projection matrix
  6265. */
  6266. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6267. var matrix = Matrix.Zero();
  6268. var n = znear;
  6269. var f = zfar;
  6270. var a = 2.0 * n / width;
  6271. var b = 2.0 * n / height;
  6272. var c = (f + n) / (f - n);
  6273. var d = -2.0 * f * n / (f - n);
  6274. 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);
  6275. return matrix;
  6276. };
  6277. /**
  6278. * Creates a left-handed perspective projection matrix
  6279. * @param fov defines the horizontal field of view
  6280. * @param aspect defines the aspect ratio
  6281. * @param znear defines the near clip plane
  6282. * @param zfar defines the far clip plane
  6283. * @returns a new matrix as a left-handed perspective projection matrix
  6284. */
  6285. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6286. var matrix = Matrix.Zero();
  6287. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6288. return matrix;
  6289. };
  6290. /**
  6291. * Stores a left-handed perspective projection into a given matrix
  6292. * @param fov defines the horizontal field of view
  6293. * @param aspect defines the aspect ratio
  6294. * @param znear defines the near clip plane
  6295. * @param zfar defines the far clip plane
  6296. * @param result defines the target matrix
  6297. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6298. */
  6299. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6300. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6301. var n = znear;
  6302. var f = zfar;
  6303. var t = 1.0 / (Math.tan(fov * 0.5));
  6304. var a = isVerticalFovFixed ? (t / aspect) : t;
  6305. var b = isVerticalFovFixed ? t : (t * aspect);
  6306. var c = (f + n) / (f - n);
  6307. var d = -2.0 * f * n / (f - n);
  6308. 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);
  6309. };
  6310. /**
  6311. * Creates a right-handed perspective projection matrix
  6312. * @param fov defines the horizontal field of view
  6313. * @param aspect defines the aspect ratio
  6314. * @param znear defines the near clip plane
  6315. * @param zfar defines the far clip plane
  6316. * @returns a new matrix as a right-handed perspective projection matrix
  6317. */
  6318. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6319. var matrix = Matrix.Zero();
  6320. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6321. return matrix;
  6322. };
  6323. /**
  6324. * Stores a right-handed perspective projection into a given matrix
  6325. * @param fov defines the horizontal field of view
  6326. * @param aspect defines the aspect ratio
  6327. * @param znear defines the near clip plane
  6328. * @param zfar defines the far clip plane
  6329. * @param result defines the target matrix
  6330. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6331. */
  6332. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6333. //alternatively this could be expressed as:
  6334. // m = PerspectiveFovLHToRef
  6335. // m[10] *= -1.0;
  6336. // m[11] *= -1.0;
  6337. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6338. var n = znear;
  6339. var f = zfar;
  6340. var t = 1.0 / (Math.tan(fov * 0.5));
  6341. var a = isVerticalFovFixed ? (t / aspect) : t;
  6342. var b = isVerticalFovFixed ? t : (t * aspect);
  6343. var c = -(f + n) / (f - n);
  6344. var d = -2 * f * n / (f - n);
  6345. 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);
  6346. };
  6347. /**
  6348. * Stores a perspective projection for WebVR info a given matrix
  6349. * @param fov defines the field of view
  6350. * @param znear defines the near clip plane
  6351. * @param zfar defines the far clip plane
  6352. * @param result defines the target matrix
  6353. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6354. */
  6355. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6356. if (rightHanded === void 0) { rightHanded = false; }
  6357. var rightHandedFactor = rightHanded ? -1 : 1;
  6358. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6359. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6360. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6361. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6362. var xScale = 2.0 / (leftTan + rightTan);
  6363. var yScale = 2.0 / (upTan + downTan);
  6364. result.m[0] = xScale;
  6365. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6366. result.m[5] = yScale;
  6367. result.m[6] = result.m[7] = 0.0;
  6368. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6369. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6370. result.m[10] = -zfar / (znear - zfar);
  6371. result.m[11] = 1.0 * rightHandedFactor;
  6372. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6373. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6374. result._markAsUpdated();
  6375. };
  6376. /**
  6377. * Computes a complete transformation matrix
  6378. * @param viewport defines the viewport to use
  6379. * @param world defines the world matrix
  6380. * @param view defines the view matrix
  6381. * @param projection defines the projection matrix
  6382. * @param zmin defines the near clip plane
  6383. * @param zmax defines the far clip plane
  6384. * @returns the transformation matrix
  6385. */
  6386. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6387. var cw = viewport.width;
  6388. var ch = viewport.height;
  6389. var cx = viewport.x;
  6390. var cy = viewport.y;
  6391. 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);
  6392. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6393. };
  6394. /**
  6395. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6396. * @param matrix defines the matrix to use
  6397. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6398. */
  6399. Matrix.GetAsMatrix2x2 = function (matrix) {
  6400. return new Float32Array([
  6401. matrix.m[0], matrix.m[1],
  6402. matrix.m[4], matrix.m[5]
  6403. ]);
  6404. };
  6405. /**
  6406. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6407. * @param matrix defines the matrix to use
  6408. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6409. */
  6410. Matrix.GetAsMatrix3x3 = function (matrix) {
  6411. return new Float32Array([
  6412. matrix.m[0], matrix.m[1], matrix.m[2],
  6413. matrix.m[4], matrix.m[5], matrix.m[6],
  6414. matrix.m[8], matrix.m[9], matrix.m[10]
  6415. ]);
  6416. };
  6417. /**
  6418. * Compute the transpose of a given matrix
  6419. * @param matrix defines the matrix to transpose
  6420. * @returns the new matrix
  6421. */
  6422. Matrix.Transpose = function (matrix) {
  6423. var result = new Matrix();
  6424. Matrix.TransposeToRef(matrix, result);
  6425. return result;
  6426. };
  6427. /**
  6428. * Compute the transpose of a matrix and store it in a target matrix
  6429. * @param matrix defines the matrix to transpose
  6430. * @param result defines the target matrix
  6431. */
  6432. Matrix.TransposeToRef = function (matrix, result) {
  6433. result.m[0] = matrix.m[0];
  6434. result.m[1] = matrix.m[4];
  6435. result.m[2] = matrix.m[8];
  6436. result.m[3] = matrix.m[12];
  6437. result.m[4] = matrix.m[1];
  6438. result.m[5] = matrix.m[5];
  6439. result.m[6] = matrix.m[9];
  6440. result.m[7] = matrix.m[13];
  6441. result.m[8] = matrix.m[2];
  6442. result.m[9] = matrix.m[6];
  6443. result.m[10] = matrix.m[10];
  6444. result.m[11] = matrix.m[14];
  6445. result.m[12] = matrix.m[3];
  6446. result.m[13] = matrix.m[7];
  6447. result.m[14] = matrix.m[11];
  6448. result.m[15] = matrix.m[15];
  6449. };
  6450. /**
  6451. * Computes a reflection matrix from a plane
  6452. * @param plane defines the reflection plane
  6453. * @returns a new matrix
  6454. */
  6455. Matrix.Reflection = function (plane) {
  6456. var matrix = new Matrix();
  6457. Matrix.ReflectionToRef(plane, matrix);
  6458. return matrix;
  6459. };
  6460. /**
  6461. * Computes a reflection matrix from a plane
  6462. * @param plane defines the reflection plane
  6463. * @param result defines the target matrix
  6464. */
  6465. Matrix.ReflectionToRef = function (plane, result) {
  6466. plane.normalize();
  6467. var x = plane.normal.x;
  6468. var y = plane.normal.y;
  6469. var z = plane.normal.z;
  6470. var temp = -2 * x;
  6471. var temp2 = -2 * y;
  6472. var temp3 = -2 * z;
  6473. result.m[0] = (temp * x) + 1;
  6474. result.m[1] = temp2 * x;
  6475. result.m[2] = temp3 * x;
  6476. result.m[3] = 0.0;
  6477. result.m[4] = temp * y;
  6478. result.m[5] = (temp2 * y) + 1;
  6479. result.m[6] = temp3 * y;
  6480. result.m[7] = 0.0;
  6481. result.m[8] = temp * z;
  6482. result.m[9] = temp2 * z;
  6483. result.m[10] = (temp3 * z) + 1;
  6484. result.m[11] = 0.0;
  6485. result.m[12] = temp * plane.d;
  6486. result.m[13] = temp2 * plane.d;
  6487. result.m[14] = temp3 * plane.d;
  6488. result.m[15] = 1.0;
  6489. result._markAsUpdated();
  6490. };
  6491. /**
  6492. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6493. * @param xaxis defines the value of the 1st axis
  6494. * @param yaxis defines the value of the 2nd axis
  6495. * @param zaxis defines the value of the 3rd axis
  6496. * @param result defines the target matrix
  6497. */
  6498. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6499. result.m[0] = xaxis.x;
  6500. result.m[1] = xaxis.y;
  6501. result.m[2] = xaxis.z;
  6502. result.m[3] = 0.0;
  6503. result.m[4] = yaxis.x;
  6504. result.m[5] = yaxis.y;
  6505. result.m[6] = yaxis.z;
  6506. result.m[7] = 0.0;
  6507. result.m[8] = zaxis.x;
  6508. result.m[9] = zaxis.y;
  6509. result.m[10] = zaxis.z;
  6510. result.m[11] = 0.0;
  6511. result.m[12] = 0.0;
  6512. result.m[13] = 0.0;
  6513. result.m[14] = 0.0;
  6514. result.m[15] = 1.0;
  6515. result._markAsUpdated();
  6516. };
  6517. /**
  6518. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6519. * @param quat defines the quaternion to use
  6520. * @param result defines the target matrix
  6521. */
  6522. Matrix.FromQuaternionToRef = function (quat, result) {
  6523. var xx = quat.x * quat.x;
  6524. var yy = quat.y * quat.y;
  6525. var zz = quat.z * quat.z;
  6526. var xy = quat.x * quat.y;
  6527. var zw = quat.z * quat.w;
  6528. var zx = quat.z * quat.x;
  6529. var yw = quat.y * quat.w;
  6530. var yz = quat.y * quat.z;
  6531. var xw = quat.x * quat.w;
  6532. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6533. result.m[1] = 2.0 * (xy + zw);
  6534. result.m[2] = 2.0 * (zx - yw);
  6535. result.m[3] = 0.0;
  6536. result.m[4] = 2.0 * (xy - zw);
  6537. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6538. result.m[6] = 2.0 * (yz + xw);
  6539. result.m[7] = 0.0;
  6540. result.m[8] = 2.0 * (zx + yw);
  6541. result.m[9] = 2.0 * (yz - xw);
  6542. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6543. result.m[11] = 0.0;
  6544. result.m[12] = 0.0;
  6545. result.m[13] = 0.0;
  6546. result.m[14] = 0.0;
  6547. result.m[15] = 1.0;
  6548. result._markAsUpdated();
  6549. };
  6550. Matrix._tempQuaternion = new Quaternion();
  6551. Matrix._xAxis = Vector3.Zero();
  6552. Matrix._yAxis = Vector3.Zero();
  6553. Matrix._zAxis = Vector3.Zero();
  6554. Matrix._updateFlagSeed = 0;
  6555. Matrix._identityReadOnly = Matrix.Identity();
  6556. return Matrix;
  6557. }());
  6558. BABYLON.Matrix = Matrix;
  6559. var Plane = /** @class */ (function () {
  6560. /**
  6561. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6562. */
  6563. function Plane(a, b, c, d) {
  6564. this.normal = new Vector3(a, b, c);
  6565. this.d = d;
  6566. }
  6567. /**
  6568. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6569. */
  6570. Plane.prototype.asArray = function () {
  6571. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6572. };
  6573. // Methods
  6574. /**
  6575. * Returns a new plane copied from the current Plane.
  6576. */
  6577. Plane.prototype.clone = function () {
  6578. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6579. };
  6580. /**
  6581. * Returns the string "Plane".
  6582. */
  6583. Plane.prototype.getClassName = function () {
  6584. return "Plane";
  6585. };
  6586. /**
  6587. * Returns the Plane hash code.
  6588. */
  6589. Plane.prototype.getHashCode = function () {
  6590. var hash = this.normal.getHashCode();
  6591. hash = (hash * 397) ^ (this.d || 0);
  6592. return hash;
  6593. };
  6594. /**
  6595. * Normalize the current Plane in place.
  6596. * Returns the updated Plane.
  6597. */
  6598. Plane.prototype.normalize = function () {
  6599. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6600. var magnitude = 0.0;
  6601. if (norm !== 0) {
  6602. magnitude = 1.0 / norm;
  6603. }
  6604. this.normal.x *= magnitude;
  6605. this.normal.y *= magnitude;
  6606. this.normal.z *= magnitude;
  6607. this.d *= magnitude;
  6608. return this;
  6609. };
  6610. /**
  6611. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6612. */
  6613. Plane.prototype.transform = function (transformation) {
  6614. var transposedMatrix = Matrix.Transpose(transformation);
  6615. var x = this.normal.x;
  6616. var y = this.normal.y;
  6617. var z = this.normal.z;
  6618. var d = this.d;
  6619. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6620. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6621. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6622. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6623. return new Plane(normalX, normalY, normalZ, finalD);
  6624. };
  6625. /**
  6626. * Returns the dot product (float) of the point coordinates and the plane normal.
  6627. */
  6628. Plane.prototype.dotCoordinate = function (point) {
  6629. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6630. };
  6631. /**
  6632. * Updates the current Plane from the plane defined by the three given points.
  6633. * Returns the updated Plane.
  6634. */
  6635. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6636. var x1 = point2.x - point1.x;
  6637. var y1 = point2.y - point1.y;
  6638. var z1 = point2.z - point1.z;
  6639. var x2 = point3.x - point1.x;
  6640. var y2 = point3.y - point1.y;
  6641. var z2 = point3.z - point1.z;
  6642. var yz = (y1 * z2) - (z1 * y2);
  6643. var xz = (z1 * x2) - (x1 * z2);
  6644. var xy = (x1 * y2) - (y1 * x2);
  6645. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6646. var invPyth;
  6647. if (pyth !== 0) {
  6648. invPyth = 1.0 / pyth;
  6649. }
  6650. else {
  6651. invPyth = 0.0;
  6652. }
  6653. this.normal.x = yz * invPyth;
  6654. this.normal.y = xz * invPyth;
  6655. this.normal.z = xy * invPyth;
  6656. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6657. return this;
  6658. };
  6659. /**
  6660. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6661. */
  6662. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6663. var dot = Vector3.Dot(this.normal, direction);
  6664. return (dot <= epsilon);
  6665. };
  6666. /**
  6667. * Returns the signed distance (float) from the given point to the Plane.
  6668. */
  6669. Plane.prototype.signedDistanceTo = function (point) {
  6670. return Vector3.Dot(point, this.normal) + this.d;
  6671. };
  6672. // Statics
  6673. /**
  6674. * Returns a new Plane from the given array.
  6675. */
  6676. Plane.FromArray = function (array) {
  6677. return new Plane(array[0], array[1], array[2], array[3]);
  6678. };
  6679. /**
  6680. * Returns a new Plane defined by the three given points.
  6681. */
  6682. Plane.FromPoints = function (point1, point2, point3) {
  6683. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6684. result.copyFromPoints(point1, point2, point3);
  6685. return result;
  6686. };
  6687. /**
  6688. * Returns a new Plane the normal vector to this plane at the given origin point.
  6689. * Note : the vector "normal" is updated because normalized.
  6690. */
  6691. Plane.FromPositionAndNormal = function (origin, normal) {
  6692. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6693. normal.normalize();
  6694. result.normal = normal;
  6695. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6696. return result;
  6697. };
  6698. /**
  6699. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6700. */
  6701. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6702. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6703. return Vector3.Dot(point, normal) + d;
  6704. };
  6705. return Plane;
  6706. }());
  6707. BABYLON.Plane = Plane;
  6708. var Viewport = /** @class */ (function () {
  6709. /**
  6710. * Creates a Viewport object located at (x, y) and sized (width, height).
  6711. */
  6712. function Viewport(x, y, width, height) {
  6713. this.x = x;
  6714. this.y = y;
  6715. this.width = width;
  6716. this.height = height;
  6717. }
  6718. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6719. if (renderWidthOrEngine.getRenderWidth) {
  6720. var engine = renderWidthOrEngine;
  6721. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6722. }
  6723. var renderWidth = renderWidthOrEngine;
  6724. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6725. };
  6726. /**
  6727. * Returns a new Viewport copied from the current one.
  6728. */
  6729. Viewport.prototype.clone = function () {
  6730. return new Viewport(this.x, this.y, this.width, this.height);
  6731. };
  6732. return Viewport;
  6733. }());
  6734. BABYLON.Viewport = Viewport;
  6735. var Frustum = /** @class */ (function () {
  6736. function Frustum() {
  6737. }
  6738. /**
  6739. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6740. */
  6741. Frustum.GetPlanes = function (transform) {
  6742. var frustumPlanes = [];
  6743. for (var index = 0; index < 6; index++) {
  6744. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6745. }
  6746. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6747. return frustumPlanes;
  6748. };
  6749. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6750. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6751. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6752. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6753. frustumPlane.d = transform.m[15] + transform.m[14];
  6754. frustumPlane.normalize();
  6755. };
  6756. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6757. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6758. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6759. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6760. frustumPlane.d = transform.m[15] - transform.m[14];
  6761. frustumPlane.normalize();
  6762. };
  6763. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6764. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6765. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6766. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6767. frustumPlane.d = transform.m[15] + transform.m[12];
  6768. frustumPlane.normalize();
  6769. };
  6770. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6771. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6772. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6773. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6774. frustumPlane.d = transform.m[15] - transform.m[12];
  6775. frustumPlane.normalize();
  6776. };
  6777. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6778. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6779. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6780. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6781. frustumPlane.d = transform.m[15] - transform.m[13];
  6782. frustumPlane.normalize();
  6783. };
  6784. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6785. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6786. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6787. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6788. frustumPlane.d = transform.m[15] + transform.m[13];
  6789. frustumPlane.normalize();
  6790. };
  6791. /**
  6792. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6793. */
  6794. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6795. // Near
  6796. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6797. // Far
  6798. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6799. // Left
  6800. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6801. // Right
  6802. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6803. // Top
  6804. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6805. // Bottom
  6806. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6807. };
  6808. return Frustum;
  6809. }());
  6810. BABYLON.Frustum = Frustum;
  6811. /** Defines supported spaces */
  6812. var Space;
  6813. (function (Space) {
  6814. /** Local (object) space */
  6815. Space[Space["LOCAL"] = 0] = "LOCAL";
  6816. /** World space */
  6817. Space[Space["WORLD"] = 1] = "WORLD";
  6818. /** Bone space */
  6819. Space[Space["BONE"] = 2] = "BONE";
  6820. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6821. /** Defines the 3 main axes */
  6822. var Axis = /** @class */ (function () {
  6823. function Axis() {
  6824. }
  6825. /** X axis */
  6826. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6827. /** Y axis */
  6828. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6829. /** Z axis */
  6830. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6831. return Axis;
  6832. }());
  6833. BABYLON.Axis = Axis;
  6834. ;
  6835. var BezierCurve = /** @class */ (function () {
  6836. function BezierCurve() {
  6837. }
  6838. /**
  6839. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6840. */
  6841. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6842. // Extract X (which is equal to time here)
  6843. var f0 = 1 - 3 * x2 + 3 * x1;
  6844. var f1 = 3 * x2 - 6 * x1;
  6845. var f2 = 3 * x1;
  6846. var refinedT = t;
  6847. for (var i = 0; i < 5; i++) {
  6848. var refinedT2 = refinedT * refinedT;
  6849. var refinedT3 = refinedT2 * refinedT;
  6850. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6851. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6852. refinedT -= (x - t) * slope;
  6853. refinedT = Math.min(1, Math.max(0, refinedT));
  6854. }
  6855. // Resolve cubic bezier for the given x
  6856. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6857. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6858. Math.pow(refinedT, 3);
  6859. };
  6860. return BezierCurve;
  6861. }());
  6862. BABYLON.BezierCurve = BezierCurve;
  6863. /**
  6864. * Defines potential orientation for back face culling
  6865. */
  6866. var Orientation;
  6867. (function (Orientation) {
  6868. /**
  6869. * Clockwise
  6870. */
  6871. Orientation[Orientation["CW"] = 0] = "CW";
  6872. /** Counter clockwise */
  6873. Orientation[Orientation["CCW"] = 1] = "CCW";
  6874. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6875. /**
  6876. * Defines angle representation
  6877. */
  6878. var Angle = /** @class */ (function () {
  6879. /**
  6880. * Creates an Angle object of "radians" radians (float).
  6881. */
  6882. function Angle(radians) {
  6883. this._radians = radians;
  6884. if (this._radians < 0.0)
  6885. this._radians += (2.0 * Math.PI);
  6886. }
  6887. /**
  6888. * Get value in degrees
  6889. * @returns the Angle value in degrees (float)
  6890. */
  6891. Angle.prototype.degrees = function () {
  6892. return this._radians * 180.0 / Math.PI;
  6893. };
  6894. /**
  6895. * Get value in radians
  6896. * @returns the Angle value in radians (float)
  6897. */
  6898. Angle.prototype.radians = function () {
  6899. return this._radians;
  6900. };
  6901. /**
  6902. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6903. * @param a defines first vector
  6904. * @param b defines second vector
  6905. * @returns a new Angle
  6906. */
  6907. Angle.BetweenTwoPoints = function (a, b) {
  6908. var delta = b.subtract(a);
  6909. var theta = Math.atan2(delta.y, delta.x);
  6910. return new Angle(theta);
  6911. };
  6912. /**
  6913. * Gets a new Angle object from the given float in radians
  6914. * @param radians defines the angle value in radians
  6915. * @returns a new Angle
  6916. */
  6917. Angle.FromRadians = function (radians) {
  6918. return new Angle(radians);
  6919. };
  6920. /**
  6921. * Gets a new Angle object from the given float in degrees
  6922. * @param degrees defines the angle value in degrees
  6923. * @returns a new Angle
  6924. */
  6925. Angle.FromDegrees = function (degrees) {
  6926. return new Angle(degrees * Math.PI / 180.0);
  6927. };
  6928. return Angle;
  6929. }());
  6930. BABYLON.Angle = Angle;
  6931. var Arc2 = /** @class */ (function () {
  6932. /**
  6933. * Creates an Arc object from the three given points : start, middle and end.
  6934. */
  6935. function Arc2(startPoint, midPoint, endPoint) {
  6936. this.startPoint = startPoint;
  6937. this.midPoint = midPoint;
  6938. this.endPoint = endPoint;
  6939. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6940. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6941. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6942. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6943. 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);
  6944. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6945. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6946. var a1 = this.startAngle.degrees();
  6947. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6948. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6949. // angles correction
  6950. if (a2 - a1 > +180.0)
  6951. a2 -= 360.0;
  6952. if (a2 - a1 < -180.0)
  6953. a2 += 360.0;
  6954. if (a3 - a2 > +180.0)
  6955. a3 -= 360.0;
  6956. if (a3 - a2 < -180.0)
  6957. a3 += 360.0;
  6958. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6959. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6960. }
  6961. return Arc2;
  6962. }());
  6963. BABYLON.Arc2 = Arc2;
  6964. var Path2 = /** @class */ (function () {
  6965. /**
  6966. * Creates a Path2 object from the starting 2D coordinates x and y.
  6967. */
  6968. function Path2(x, y) {
  6969. this._points = new Array();
  6970. this._length = 0.0;
  6971. this.closed = false;
  6972. this._points.push(new Vector2(x, y));
  6973. }
  6974. /**
  6975. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6976. * Returns the updated Path2.
  6977. */
  6978. Path2.prototype.addLineTo = function (x, y) {
  6979. if (this.closed) {
  6980. return this;
  6981. }
  6982. var newPoint = new Vector2(x, y);
  6983. var previousPoint = this._points[this._points.length - 1];
  6984. this._points.push(newPoint);
  6985. this._length += newPoint.subtract(previousPoint).length();
  6986. return this;
  6987. };
  6988. /**
  6989. * 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.
  6990. * Returns the updated Path2.
  6991. */
  6992. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6993. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6994. if (this.closed) {
  6995. return this;
  6996. }
  6997. var startPoint = this._points[this._points.length - 1];
  6998. var midPoint = new Vector2(midX, midY);
  6999. var endPoint = new Vector2(endX, endY);
  7000. var arc = new Arc2(startPoint, midPoint, endPoint);
  7001. var increment = arc.angle.radians() / numberOfSegments;
  7002. if (arc.orientation === Orientation.CW)
  7003. increment *= -1;
  7004. var currentAngle = arc.startAngle.radians() + increment;
  7005. for (var i = 0; i < numberOfSegments; i++) {
  7006. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7007. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7008. this.addLineTo(x, y);
  7009. currentAngle += increment;
  7010. }
  7011. return this;
  7012. };
  7013. /**
  7014. * Closes the Path2.
  7015. * Returns the Path2.
  7016. */
  7017. Path2.prototype.close = function () {
  7018. this.closed = true;
  7019. return this;
  7020. };
  7021. /**
  7022. * Returns the Path2 total length (float).
  7023. */
  7024. Path2.prototype.length = function () {
  7025. var result = this._length;
  7026. if (!this.closed) {
  7027. var lastPoint = this._points[this._points.length - 1];
  7028. var firstPoint = this._points[0];
  7029. result += (firstPoint.subtract(lastPoint).length());
  7030. }
  7031. return result;
  7032. };
  7033. /**
  7034. * Returns the Path2 internal array of points.
  7035. */
  7036. Path2.prototype.getPoints = function () {
  7037. return this._points;
  7038. };
  7039. /**
  7040. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7041. */
  7042. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7043. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7044. return Vector2.Zero();
  7045. }
  7046. var lengthPosition = normalizedLengthPosition * this.length();
  7047. var previousOffset = 0;
  7048. for (var i = 0; i < this._points.length; i++) {
  7049. var j = (i + 1) % this._points.length;
  7050. var a = this._points[i];
  7051. var b = this._points[j];
  7052. var bToA = b.subtract(a);
  7053. var nextOffset = (bToA.length() + previousOffset);
  7054. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7055. var dir = bToA.normalize();
  7056. var localOffset = lengthPosition - previousOffset;
  7057. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7058. }
  7059. previousOffset = nextOffset;
  7060. }
  7061. return Vector2.Zero();
  7062. };
  7063. /**
  7064. * Returns a new Path2 starting at the coordinates (x, y).
  7065. */
  7066. Path2.StartingAt = function (x, y) {
  7067. return new Path2(x, y);
  7068. };
  7069. return Path2;
  7070. }());
  7071. BABYLON.Path2 = Path2;
  7072. var Path3D = /** @class */ (function () {
  7073. /**
  7074. * new Path3D(path, normal, raw)
  7075. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7076. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7077. * path : an array of Vector3, the curve axis of the Path3D
  7078. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7079. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7080. */
  7081. function Path3D(path, firstNormal, raw) {
  7082. if (firstNormal === void 0) { firstNormal = null; }
  7083. this.path = path;
  7084. this._curve = new Array();
  7085. this._distances = new Array();
  7086. this._tangents = new Array();
  7087. this._normals = new Array();
  7088. this._binormals = new Array();
  7089. for (var p = 0; p < path.length; p++) {
  7090. this._curve[p] = path[p].clone(); // hard copy
  7091. }
  7092. this._raw = raw || false;
  7093. this._compute(firstNormal);
  7094. }
  7095. /**
  7096. * Returns the Path3D array of successive Vector3 designing its curve.
  7097. */
  7098. Path3D.prototype.getCurve = function () {
  7099. return this._curve;
  7100. };
  7101. /**
  7102. * Returns an array populated with tangent vectors on each Path3D curve point.
  7103. */
  7104. Path3D.prototype.getTangents = function () {
  7105. return this._tangents;
  7106. };
  7107. /**
  7108. * Returns an array populated with normal vectors on each Path3D curve point.
  7109. */
  7110. Path3D.prototype.getNormals = function () {
  7111. return this._normals;
  7112. };
  7113. /**
  7114. * Returns an array populated with binormal vectors on each Path3D curve point.
  7115. */
  7116. Path3D.prototype.getBinormals = function () {
  7117. return this._binormals;
  7118. };
  7119. /**
  7120. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7121. */
  7122. Path3D.prototype.getDistances = function () {
  7123. return this._distances;
  7124. };
  7125. /**
  7126. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7127. * Returns the same object updated.
  7128. */
  7129. Path3D.prototype.update = function (path, firstNormal) {
  7130. if (firstNormal === void 0) { firstNormal = null; }
  7131. for (var p = 0; p < path.length; p++) {
  7132. this._curve[p].x = path[p].x;
  7133. this._curve[p].y = path[p].y;
  7134. this._curve[p].z = path[p].z;
  7135. }
  7136. this._compute(firstNormal);
  7137. return this;
  7138. };
  7139. // private function compute() : computes tangents, normals and binormals
  7140. Path3D.prototype._compute = function (firstNormal) {
  7141. var l = this._curve.length;
  7142. // first and last tangents
  7143. this._tangents[0] = this._getFirstNonNullVector(0);
  7144. if (!this._raw) {
  7145. this._tangents[0].normalize();
  7146. }
  7147. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7148. if (!this._raw) {
  7149. this._tangents[l - 1].normalize();
  7150. }
  7151. // normals and binormals at first point : arbitrary vector with _normalVector()
  7152. var tg0 = this._tangents[0];
  7153. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7154. this._normals[0] = pp0;
  7155. if (!this._raw) {
  7156. this._normals[0].normalize();
  7157. }
  7158. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7159. if (!this._raw) {
  7160. this._binormals[0].normalize();
  7161. }
  7162. this._distances[0] = 0.0;
  7163. // normals and binormals : next points
  7164. var prev; // previous vector (segment)
  7165. var cur; // current vector (segment)
  7166. var curTang; // current tangent
  7167. // previous normal
  7168. var prevBinor; // previous binormal
  7169. for (var i = 1; i < l; i++) {
  7170. // tangents
  7171. prev = this._getLastNonNullVector(i);
  7172. if (i < l - 1) {
  7173. cur = this._getFirstNonNullVector(i);
  7174. this._tangents[i] = prev.add(cur);
  7175. this._tangents[i].normalize();
  7176. }
  7177. this._distances[i] = this._distances[i - 1] + prev.length();
  7178. // normals and binormals
  7179. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7180. curTang = this._tangents[i];
  7181. prevBinor = this._binormals[i - 1];
  7182. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7183. if (!this._raw) {
  7184. this._normals[i].normalize();
  7185. }
  7186. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7187. if (!this._raw) {
  7188. this._binormals[i].normalize();
  7189. }
  7190. }
  7191. };
  7192. // private function getFirstNonNullVector(index)
  7193. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7194. Path3D.prototype._getFirstNonNullVector = function (index) {
  7195. var i = 1;
  7196. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7197. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7198. i++;
  7199. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7200. }
  7201. return nNVector;
  7202. };
  7203. // private function getLastNonNullVector(index)
  7204. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7205. Path3D.prototype._getLastNonNullVector = function (index) {
  7206. var i = 1;
  7207. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7208. while (nLVector.length() === 0 && index > i + 1) {
  7209. i++;
  7210. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7211. }
  7212. return nLVector;
  7213. };
  7214. // private function normalVector(v0, vt, va) :
  7215. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7216. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7217. Path3D.prototype._normalVector = function (v0, vt, va) {
  7218. var normal0;
  7219. var tgl = vt.length();
  7220. if (tgl === 0.0) {
  7221. tgl = 1.0;
  7222. }
  7223. if (va === undefined || va === null) {
  7224. var point;
  7225. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7226. point = new Vector3(0.0, -1.0, 0.0);
  7227. }
  7228. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7229. point = new Vector3(1.0, 0.0, 0.0);
  7230. }
  7231. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7232. point = new Vector3(0.0, 0.0, 1.0);
  7233. }
  7234. else {
  7235. point = Vector3.Zero();
  7236. }
  7237. normal0 = Vector3.Cross(vt, point);
  7238. }
  7239. else {
  7240. normal0 = Vector3.Cross(vt, va);
  7241. Vector3.CrossToRef(normal0, vt, normal0);
  7242. }
  7243. normal0.normalize();
  7244. return normal0;
  7245. };
  7246. return Path3D;
  7247. }());
  7248. BABYLON.Path3D = Path3D;
  7249. var Curve3 = /** @class */ (function () {
  7250. /**
  7251. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7252. * A Curve3 is designed from a series of successive Vector3.
  7253. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7254. */
  7255. function Curve3(points) {
  7256. this._length = 0.0;
  7257. this._points = points;
  7258. this._length = this._computeLength(points);
  7259. }
  7260. /**
  7261. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7262. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7263. * @param v1 (Vector3) the control point
  7264. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7265. * @param nbPoints (integer) the wanted number of points in the curve
  7266. */
  7267. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7268. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7269. var bez = new Array();
  7270. var equation = function (t, val0, val1, val2) {
  7271. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7272. return res;
  7273. };
  7274. for (var i = 0; i <= nbPoints; i++) {
  7275. 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)));
  7276. }
  7277. return new Curve3(bez);
  7278. };
  7279. /**
  7280. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7281. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7282. * @param v1 (Vector3) the first control point
  7283. * @param v2 (Vector3) the second control point
  7284. * @param v3 (Vector3) the end point of the Cubic Bezier
  7285. * @param nbPoints (integer) the wanted number of points in the curve
  7286. */
  7287. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7288. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7289. var bez = new Array();
  7290. var equation = function (t, val0, val1, val2, val3) {
  7291. 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;
  7292. return res;
  7293. };
  7294. for (var i = 0; i <= nbPoints; i++) {
  7295. 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)));
  7296. }
  7297. return new Curve3(bez);
  7298. };
  7299. /**
  7300. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7301. * @param p1 (Vector3) the origin point of the Hermite Spline
  7302. * @param t1 (Vector3) the tangent vector at the origin point
  7303. * @param p2 (Vector3) the end point of the Hermite Spline
  7304. * @param t2 (Vector3) the tangent vector at the end point
  7305. * @param nbPoints (integer) the wanted number of points in the curve
  7306. */
  7307. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7308. var hermite = new Array();
  7309. var step = 1.0 / nbPoints;
  7310. for (var i = 0; i <= nbPoints; i++) {
  7311. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7312. }
  7313. return new Curve3(hermite);
  7314. };
  7315. /**
  7316. * Returns a Curve3 object along a CatmullRom Spline curve :
  7317. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7318. * @param nbPoints (integer) the wanted number of points between each curve control points
  7319. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7320. */
  7321. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7322. var catmullRom = new Array();
  7323. var step = 1.0 / nbPoints;
  7324. var amount = 0.0;
  7325. if (closed) {
  7326. var pointsCount = points.length;
  7327. for (var i = 0; i < pointsCount; i++) {
  7328. amount = 0;
  7329. for (var c = 0; c < nbPoints; c++) {
  7330. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7331. amount += step;
  7332. }
  7333. }
  7334. catmullRom.push(catmullRom[0]);
  7335. }
  7336. else {
  7337. var totalPoints = new Array();
  7338. totalPoints.push(points[0].clone());
  7339. Array.prototype.push.apply(totalPoints, points);
  7340. totalPoints.push(points[points.length - 1].clone());
  7341. for (var i = 0; i < totalPoints.length - 3; i++) {
  7342. amount = 0;
  7343. for (var c = 0; c < nbPoints; c++) {
  7344. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7345. amount += step;
  7346. }
  7347. }
  7348. i--;
  7349. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7350. }
  7351. return new Curve3(catmullRom);
  7352. };
  7353. /**
  7354. * Returns the Curve3 stored array of successive Vector3
  7355. */
  7356. Curve3.prototype.getPoints = function () {
  7357. return this._points;
  7358. };
  7359. /**
  7360. * Returns the computed length (float) of the curve.
  7361. */
  7362. Curve3.prototype.length = function () {
  7363. return this._length;
  7364. };
  7365. /**
  7366. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7367. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7368. * curveA and curveB keep unchanged.
  7369. */
  7370. Curve3.prototype.continue = function (curve) {
  7371. var lastPoint = this._points[this._points.length - 1];
  7372. var continuedPoints = this._points.slice();
  7373. var curvePoints = curve.getPoints();
  7374. for (var i = 1; i < curvePoints.length; i++) {
  7375. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7376. }
  7377. var continuedCurve = new Curve3(continuedPoints);
  7378. return continuedCurve;
  7379. };
  7380. Curve3.prototype._computeLength = function (path) {
  7381. var l = 0;
  7382. for (var i = 1; i < path.length; i++) {
  7383. l += (path[i].subtract(path[i - 1])).length();
  7384. }
  7385. return l;
  7386. };
  7387. return Curve3;
  7388. }());
  7389. BABYLON.Curve3 = Curve3;
  7390. // Vertex formats
  7391. var PositionNormalVertex = /** @class */ (function () {
  7392. function PositionNormalVertex(position, normal) {
  7393. if (position === void 0) { position = Vector3.Zero(); }
  7394. if (normal === void 0) { normal = Vector3.Up(); }
  7395. this.position = position;
  7396. this.normal = normal;
  7397. }
  7398. PositionNormalVertex.prototype.clone = function () {
  7399. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7400. };
  7401. return PositionNormalVertex;
  7402. }());
  7403. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7404. var PositionNormalTextureVertex = /** @class */ (function () {
  7405. function PositionNormalTextureVertex(position, normal, uv) {
  7406. if (position === void 0) { position = Vector3.Zero(); }
  7407. if (normal === void 0) { normal = Vector3.Up(); }
  7408. if (uv === void 0) { uv = Vector2.Zero(); }
  7409. this.position = position;
  7410. this.normal = normal;
  7411. this.uv = uv;
  7412. }
  7413. PositionNormalTextureVertex.prototype.clone = function () {
  7414. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7415. };
  7416. return PositionNormalTextureVertex;
  7417. }());
  7418. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7419. // Temporary pre-allocated objects for engine internal use
  7420. // usage in any internal function :
  7421. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7422. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7423. var Tmp = /** @class */ (function () {
  7424. function Tmp() {
  7425. }
  7426. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7427. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7428. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7429. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7430. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7431. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7432. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7433. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7434. Matrix.Zero(), Matrix.Zero(),
  7435. Matrix.Zero(), Matrix.Zero(),
  7436. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7437. return Tmp;
  7438. }());
  7439. BABYLON.Tmp = Tmp;
  7440. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7441. var MathTmp = /** @class */ (function () {
  7442. function MathTmp() {
  7443. }
  7444. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7445. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7446. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7447. return MathTmp;
  7448. }());
  7449. })(BABYLON || (BABYLON = {}));
  7450. //# sourceMappingURL=babylon.math.js.map
  7451. var BABYLON;
  7452. (function (BABYLON) {
  7453. var Scalar = /** @class */ (function () {
  7454. function Scalar() {
  7455. }
  7456. /**
  7457. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7458. */
  7459. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7460. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7461. var num = a - b;
  7462. return -epsilon <= num && num <= epsilon;
  7463. };
  7464. /**
  7465. * Returns a string : the upper case translation of the number i to hexadecimal.
  7466. */
  7467. Scalar.ToHex = function (i) {
  7468. var str = i.toString(16);
  7469. if (i <= 15) {
  7470. return ("0" + str).toUpperCase();
  7471. }
  7472. return str.toUpperCase();
  7473. };
  7474. /**
  7475. * Returns -1 if value is negative and +1 is value is positive.
  7476. * Returns the value itself if it's equal to zero.
  7477. */
  7478. Scalar.Sign = function (value) {
  7479. value = +value; // convert to a number
  7480. if (value === 0 || isNaN(value))
  7481. return value;
  7482. return value > 0 ? 1 : -1;
  7483. };
  7484. /**
  7485. * Returns the value itself if it's between min and max.
  7486. * Returns min if the value is lower than min.
  7487. * Returns max if the value is greater than max.
  7488. */
  7489. Scalar.Clamp = function (value, min, max) {
  7490. if (min === void 0) { min = 0; }
  7491. if (max === void 0) { max = 1; }
  7492. return Math.min(max, Math.max(min, value));
  7493. };
  7494. /**
  7495. * Returns the log2 of value.
  7496. */
  7497. Scalar.Log2 = function (value) {
  7498. return Math.log(value) * Math.LOG2E;
  7499. };
  7500. /**
  7501. * Loops the value, so that it is never larger than length and never smaller than 0.
  7502. *
  7503. * This is similar to the modulo operator but it works with floating point numbers.
  7504. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7505. * With t = 5 and length = 2.5, the result would be 0.0.
  7506. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7507. */
  7508. Scalar.Repeat = function (value, length) {
  7509. return value - Math.floor(value / length) * length;
  7510. };
  7511. /**
  7512. * Normalize the value between 0.0 and 1.0 using min and max values
  7513. */
  7514. Scalar.Normalize = function (value, min, max) {
  7515. return (value - min) / (max - min);
  7516. };
  7517. /**
  7518. * Denormalize the value from 0.0 and 1.0 using min and max values
  7519. */
  7520. Scalar.Denormalize = function (normalized, min, max) {
  7521. return (normalized * (max - min) + min);
  7522. };
  7523. /**
  7524. * Calculates the shortest difference between two given angles given in degrees.
  7525. */
  7526. Scalar.DeltaAngle = function (current, target) {
  7527. var num = Scalar.Repeat(target - current, 360.0);
  7528. if (num > 180.0) {
  7529. num -= 360.0;
  7530. }
  7531. return num;
  7532. };
  7533. /**
  7534. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7535. *
  7536. * The returned value will move back and forth between 0 and length
  7537. */
  7538. Scalar.PingPong = function (tx, length) {
  7539. var t = Scalar.Repeat(tx, length * 2.0);
  7540. return length - Math.abs(t - length);
  7541. };
  7542. /**
  7543. * Interpolates between min and max with smoothing at the limits.
  7544. *
  7545. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7546. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7547. */
  7548. Scalar.SmoothStep = function (from, to, tx) {
  7549. var t = Scalar.Clamp(tx);
  7550. t = -2.0 * t * t * t + 3.0 * t * t;
  7551. return to * t + from * (1.0 - t);
  7552. };
  7553. /**
  7554. * Moves a value current towards target.
  7555. *
  7556. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7557. * Negative values of maxDelta pushes the value away from target.
  7558. */
  7559. Scalar.MoveTowards = function (current, target, maxDelta) {
  7560. var result = 0;
  7561. if (Math.abs(target - current) <= maxDelta) {
  7562. result = target;
  7563. }
  7564. else {
  7565. result = current + Scalar.Sign(target - current) * maxDelta;
  7566. }
  7567. return result;
  7568. };
  7569. /**
  7570. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7571. *
  7572. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7573. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7574. */
  7575. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7576. var num = Scalar.DeltaAngle(current, target);
  7577. var result = 0;
  7578. if (-maxDelta < num && num < maxDelta) {
  7579. result = target;
  7580. }
  7581. else {
  7582. target = current + num;
  7583. result = Scalar.MoveTowards(current, target, maxDelta);
  7584. }
  7585. return result;
  7586. };
  7587. /**
  7588. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7589. */
  7590. Scalar.Lerp = function (start, end, amount) {
  7591. return start + ((end - start) * amount);
  7592. };
  7593. /**
  7594. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7595. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7596. */
  7597. Scalar.LerpAngle = function (start, end, amount) {
  7598. var num = Scalar.Repeat(end - start, 360.0);
  7599. if (num > 180.0) {
  7600. num -= 360.0;
  7601. }
  7602. return start + num * Scalar.Clamp(amount);
  7603. };
  7604. /**
  7605. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7606. */
  7607. Scalar.InverseLerp = function (a, b, value) {
  7608. var result = 0;
  7609. if (a != b) {
  7610. result = Scalar.Clamp((value - a) / (b - a));
  7611. }
  7612. else {
  7613. result = 0.0;
  7614. }
  7615. return result;
  7616. };
  7617. /**
  7618. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7619. */
  7620. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7621. var squared = amount * amount;
  7622. var cubed = amount * squared;
  7623. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7624. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7625. var part3 = (cubed - (2.0 * squared)) + amount;
  7626. var part4 = cubed - squared;
  7627. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7628. };
  7629. /**
  7630. * Returns a random float number between and min and max values
  7631. */
  7632. Scalar.RandomRange = function (min, max) {
  7633. if (min === max)
  7634. return min;
  7635. return ((Math.random() * (max - min)) + min);
  7636. };
  7637. /**
  7638. * This function returns percentage of a number in a given range.
  7639. *
  7640. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7641. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7642. */
  7643. Scalar.RangeToPercent = function (number, min, max) {
  7644. return ((number - min) / (max - min));
  7645. };
  7646. /**
  7647. * This function returns number that corresponds to the percentage in a given range.
  7648. *
  7649. * PercentToRange(0.34,0,100) will return 34.
  7650. */
  7651. Scalar.PercentToRange = function (percent, min, max) {
  7652. return ((max - min) * percent + min);
  7653. };
  7654. /**
  7655. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7656. * @param angle The angle to normalize in radian.
  7657. * @return The converted angle.
  7658. */
  7659. Scalar.NormalizeRadians = function (angle) {
  7660. // More precise but slower version kept for reference.
  7661. // angle = angle % Tools.TwoPi;
  7662. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7663. //if (angle > Math.PI) {
  7664. // angle -= Tools.TwoPi;
  7665. //}
  7666. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7667. return angle;
  7668. };
  7669. /**
  7670. * Two pi constants convenient for computation.
  7671. */
  7672. Scalar.TwoPi = Math.PI * 2;
  7673. return Scalar;
  7674. }());
  7675. BABYLON.Scalar = Scalar;
  7676. })(BABYLON || (BABYLON = {}));
  7677. //# sourceMappingURL=babylon.math.scalar.js.map
  7678. //# sourceMappingURL=babylon.mixins.js.map
  7679. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7680. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7681. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7682. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7683. //# sourceMappingURL=babylon.webgl2.js.map
  7684. var BABYLON;
  7685. (function (BABYLON) {
  7686. var __decoratorInitialStore = {};
  7687. var __mergedStore = {};
  7688. var _copySource = function (creationFunction, source, instanciate) {
  7689. var destination = creationFunction();
  7690. // Tags
  7691. if (BABYLON.Tags) {
  7692. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7693. }
  7694. var classStore = getMergedStore(destination);
  7695. // Properties
  7696. for (var property in classStore) {
  7697. var propertyDescriptor = classStore[property];
  7698. var sourceProperty = source[property];
  7699. var propertyType = propertyDescriptor.type;
  7700. if (sourceProperty !== undefined && sourceProperty !== null) {
  7701. switch (propertyType) {
  7702. case 0: // Value
  7703. case 6: // Mesh reference
  7704. case 11: // Camera reference
  7705. destination[property] = sourceProperty;
  7706. break;
  7707. case 1: // Texture
  7708. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7709. break;
  7710. case 2: // Color3
  7711. case 3: // FresnelParameters
  7712. case 4: // Vector2
  7713. case 5: // Vector3
  7714. case 7: // Color Curves
  7715. case 10: // Quaternion
  7716. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7717. break;
  7718. }
  7719. }
  7720. }
  7721. return destination;
  7722. };
  7723. function getDirectStore(target) {
  7724. var classKey = target.getClassName();
  7725. if (!__decoratorInitialStore[classKey]) {
  7726. __decoratorInitialStore[classKey] = {};
  7727. }
  7728. return __decoratorInitialStore[classKey];
  7729. }
  7730. /**
  7731. * Return the list of properties flagged as serializable
  7732. * @param target: host object
  7733. */
  7734. function getMergedStore(target) {
  7735. var classKey = target.getClassName();
  7736. if (__mergedStore[classKey]) {
  7737. return __mergedStore[classKey];
  7738. }
  7739. __mergedStore[classKey] = {};
  7740. var store = __mergedStore[classKey];
  7741. var currentTarget = target;
  7742. var currentKey = classKey;
  7743. while (currentKey) {
  7744. var initialStore = __decoratorInitialStore[currentKey];
  7745. for (var property in initialStore) {
  7746. store[property] = initialStore[property];
  7747. }
  7748. var parent_1 = void 0;
  7749. var done = false;
  7750. do {
  7751. parent_1 = Object.getPrototypeOf(currentTarget);
  7752. if (!parent_1.getClassName) {
  7753. done = true;
  7754. break;
  7755. }
  7756. if (parent_1.getClassName() !== currentKey) {
  7757. break;
  7758. }
  7759. currentTarget = parent_1;
  7760. } while (parent_1);
  7761. if (done) {
  7762. break;
  7763. }
  7764. currentKey = parent_1.getClassName();
  7765. currentTarget = parent_1;
  7766. }
  7767. return store;
  7768. }
  7769. function generateSerializableMember(type, sourceName) {
  7770. return function (target, propertyKey) {
  7771. var classStore = getDirectStore(target);
  7772. if (!classStore[propertyKey]) {
  7773. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7774. }
  7775. };
  7776. }
  7777. function generateExpandMember(setCallback, targetKey) {
  7778. if (targetKey === void 0) { targetKey = null; }
  7779. return function (target, propertyKey) {
  7780. var key = targetKey || ("_" + propertyKey);
  7781. Object.defineProperty(target, propertyKey, {
  7782. get: function () {
  7783. return this[key];
  7784. },
  7785. set: function (value) {
  7786. if (this[key] === value) {
  7787. return;
  7788. }
  7789. this[key] = value;
  7790. target[setCallback].apply(this);
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. };
  7796. }
  7797. function expandToProperty(callback, targetKey) {
  7798. if (targetKey === void 0) { targetKey = null; }
  7799. return generateExpandMember(callback, targetKey);
  7800. }
  7801. BABYLON.expandToProperty = expandToProperty;
  7802. function serialize(sourceName) {
  7803. return generateSerializableMember(0, sourceName); // value member
  7804. }
  7805. BABYLON.serialize = serialize;
  7806. function serializeAsTexture(sourceName) {
  7807. return generateSerializableMember(1, sourceName); // texture member
  7808. }
  7809. BABYLON.serializeAsTexture = serializeAsTexture;
  7810. function serializeAsColor3(sourceName) {
  7811. return generateSerializableMember(2, sourceName); // color3 member
  7812. }
  7813. BABYLON.serializeAsColor3 = serializeAsColor3;
  7814. function serializeAsFresnelParameters(sourceName) {
  7815. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7816. }
  7817. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7818. function serializeAsVector2(sourceName) {
  7819. return generateSerializableMember(4, sourceName); // vector2 member
  7820. }
  7821. BABYLON.serializeAsVector2 = serializeAsVector2;
  7822. function serializeAsVector3(sourceName) {
  7823. return generateSerializableMember(5, sourceName); // vector3 member
  7824. }
  7825. BABYLON.serializeAsVector3 = serializeAsVector3;
  7826. function serializeAsMeshReference(sourceName) {
  7827. return generateSerializableMember(6, sourceName); // mesh reference member
  7828. }
  7829. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7830. function serializeAsColorCurves(sourceName) {
  7831. return generateSerializableMember(7, sourceName); // color curves
  7832. }
  7833. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7834. function serializeAsColor4(sourceName) {
  7835. return generateSerializableMember(8, sourceName); // color 4
  7836. }
  7837. BABYLON.serializeAsColor4 = serializeAsColor4;
  7838. function serializeAsImageProcessingConfiguration(sourceName) {
  7839. return generateSerializableMember(9, sourceName); // image processing
  7840. }
  7841. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7842. function serializeAsQuaternion(sourceName) {
  7843. return generateSerializableMember(10, sourceName); // quaternion member
  7844. }
  7845. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7846. /**
  7847. * Decorator used to define property that can be serialized as reference to a camera
  7848. * @param sourceName defines the name of the property to decorate
  7849. */
  7850. function serializeAsCameraReference(sourceName) {
  7851. return generateSerializableMember(11, sourceName); // camera reference member
  7852. }
  7853. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7854. var SerializationHelper = /** @class */ (function () {
  7855. function SerializationHelper() {
  7856. }
  7857. SerializationHelper.Serialize = function (entity, serializationObject) {
  7858. if (!serializationObject) {
  7859. serializationObject = {};
  7860. }
  7861. // Tags
  7862. if (BABYLON.Tags) {
  7863. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7864. }
  7865. var serializedProperties = getMergedStore(entity);
  7866. // Properties
  7867. for (var property in serializedProperties) {
  7868. var propertyDescriptor = serializedProperties[property];
  7869. var targetPropertyName = propertyDescriptor.sourceName || property;
  7870. var propertyType = propertyDescriptor.type;
  7871. var sourceProperty = entity[property];
  7872. if (sourceProperty !== undefined && sourceProperty !== null) {
  7873. switch (propertyType) {
  7874. case 0: // Value
  7875. serializationObject[targetPropertyName] = sourceProperty;
  7876. break;
  7877. case 1: // Texture
  7878. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7879. break;
  7880. case 2: // Color3
  7881. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7882. break;
  7883. case 3: // FresnelParameters
  7884. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7885. break;
  7886. case 4: // Vector2
  7887. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7888. break;
  7889. case 5: // Vector3
  7890. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7891. break;
  7892. case 6: // Mesh reference
  7893. serializationObject[targetPropertyName] = sourceProperty.id;
  7894. break;
  7895. case 7: // Color Curves
  7896. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7897. break;
  7898. case 8: // Color 4
  7899. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7900. break;
  7901. case 9: // Image Processing
  7902. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7903. break;
  7904. case 10: // Quaternion
  7905. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7906. break;
  7907. case 11: // Camera reference
  7908. serializationObject[targetPropertyName] = sourceProperty.id;
  7909. break;
  7910. }
  7911. }
  7912. }
  7913. return serializationObject;
  7914. };
  7915. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7916. if (rootUrl === void 0) { rootUrl = null; }
  7917. var destination = creationFunction();
  7918. if (!rootUrl) {
  7919. rootUrl = "";
  7920. }
  7921. // Tags
  7922. if (BABYLON.Tags) {
  7923. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7924. }
  7925. var classStore = getMergedStore(destination);
  7926. // Properties
  7927. for (var property in classStore) {
  7928. var propertyDescriptor = classStore[property];
  7929. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7930. var propertyType = propertyDescriptor.type;
  7931. if (sourceProperty !== undefined && sourceProperty !== null) {
  7932. var dest = destination;
  7933. switch (propertyType) {
  7934. case 0: // Value
  7935. dest[property] = sourceProperty;
  7936. break;
  7937. case 1: // Texture
  7938. if (scene) {
  7939. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7940. }
  7941. break;
  7942. case 2: // Color3
  7943. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7944. break;
  7945. case 3: // FresnelParameters
  7946. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7947. break;
  7948. case 4: // Vector2
  7949. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7950. break;
  7951. case 5: // Vector3
  7952. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7953. break;
  7954. case 6: // Mesh reference
  7955. if (scene) {
  7956. dest[property] = scene.getLastMeshByID(sourceProperty);
  7957. }
  7958. break;
  7959. case 7: // Color Curves
  7960. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7961. break;
  7962. case 8: // Color 4
  7963. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7964. break;
  7965. case 9: // Image Processing
  7966. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7967. break;
  7968. case 10: // Quaternion
  7969. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7970. break;
  7971. case 11: // Camera reference
  7972. if (scene) {
  7973. dest[property] = scene.getCameraByID(sourceProperty);
  7974. }
  7975. break;
  7976. }
  7977. }
  7978. }
  7979. return destination;
  7980. };
  7981. SerializationHelper.Clone = function (creationFunction, source) {
  7982. return _copySource(creationFunction, source, false);
  7983. };
  7984. SerializationHelper.Instanciate = function (creationFunction, source) {
  7985. return _copySource(creationFunction, source, true);
  7986. };
  7987. return SerializationHelper;
  7988. }());
  7989. BABYLON.SerializationHelper = SerializationHelper;
  7990. })(BABYLON || (BABYLON = {}));
  7991. //# sourceMappingURL=babylon.decorators.js.map
  7992. var BABYLON;
  7993. (function (BABYLON) {
  7994. /**
  7995. * Wrapper class for promise with external resolve and reject.
  7996. */
  7997. var Deferred = /** @class */ (function () {
  7998. /**
  7999. * Constructor for this deferred object.
  8000. */
  8001. function Deferred() {
  8002. var _this = this;
  8003. this.promise = new Promise(function (resolve, reject) {
  8004. _this._resolve = resolve;
  8005. _this._reject = reject;
  8006. });
  8007. }
  8008. Object.defineProperty(Deferred.prototype, "resolve", {
  8009. /**
  8010. * The resolve method of the promise associated with this deferred object.
  8011. */
  8012. get: function () {
  8013. return this._resolve;
  8014. },
  8015. enumerable: true,
  8016. configurable: true
  8017. });
  8018. Object.defineProperty(Deferred.prototype, "reject", {
  8019. /**
  8020. * The reject method of the promise associated with this deferred object.
  8021. */
  8022. get: function () {
  8023. return this._reject;
  8024. },
  8025. enumerable: true,
  8026. configurable: true
  8027. });
  8028. return Deferred;
  8029. }());
  8030. BABYLON.Deferred = Deferred;
  8031. })(BABYLON || (BABYLON = {}));
  8032. //# sourceMappingURL=babylon.deferred.js.map
  8033. var BABYLON;
  8034. (function (BABYLON) {
  8035. /**
  8036. * A class serves as a medium between the observable and its observers
  8037. */
  8038. var EventState = /** @class */ (function () {
  8039. /**
  8040. * Create a new EventState
  8041. * @param mask defines the mask associated with this state
  8042. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8043. * @param target defines the original target of the state
  8044. * @param currentTarget defines the current target of the state
  8045. */
  8046. function EventState(mask, skipNextObservers, target, currentTarget) {
  8047. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8048. this.initalize(mask, skipNextObservers, target, currentTarget);
  8049. }
  8050. /**
  8051. * Initialize the current event state
  8052. * @param mask defines the mask associated with this state
  8053. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8054. * @param target defines the original target of the state
  8055. * @param currentTarget defines the current target of the state
  8056. * @returns the current event state
  8057. */
  8058. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8059. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8060. this.mask = mask;
  8061. this.skipNextObservers = skipNextObservers;
  8062. this.target = target;
  8063. this.currentTarget = currentTarget;
  8064. return this;
  8065. };
  8066. return EventState;
  8067. }());
  8068. BABYLON.EventState = EventState;
  8069. /**
  8070. * Represent an Observer registered to a given Observable object.
  8071. */
  8072. var Observer = /** @class */ (function () {
  8073. /**
  8074. * Creates a new observer
  8075. * @param callback defines the callback to call when the observer is notified
  8076. * @param mask defines the mask of the observer (used to filter notifications)
  8077. * @param scope defines the current scope used to restore the JS context
  8078. */
  8079. function Observer(
  8080. /**
  8081. * Defines the callback to call when the observer is notified
  8082. */
  8083. callback,
  8084. /**
  8085. * Defines the mask of the observer (used to filter notifications)
  8086. */
  8087. mask,
  8088. /**
  8089. * Defines the current scope used to restore the JS context
  8090. */
  8091. scope) {
  8092. if (scope === void 0) { scope = null; }
  8093. this.callback = callback;
  8094. this.mask = mask;
  8095. this.scope = scope;
  8096. /** @hidden */
  8097. this._willBeUnregistered = false;
  8098. /**
  8099. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8100. */
  8101. this.unregisterOnNextCall = false;
  8102. }
  8103. return Observer;
  8104. }());
  8105. BABYLON.Observer = Observer;
  8106. /**
  8107. * Represent a list of observers registered to multiple Observables object.
  8108. */
  8109. var MultiObserver = /** @class */ (function () {
  8110. function MultiObserver() {
  8111. }
  8112. /**
  8113. * Release associated resources
  8114. */
  8115. MultiObserver.prototype.dispose = function () {
  8116. if (this._observers && this._observables) {
  8117. for (var index = 0; index < this._observers.length; index++) {
  8118. this._observables[index].remove(this._observers[index]);
  8119. }
  8120. }
  8121. this._observers = null;
  8122. this._observables = null;
  8123. };
  8124. /**
  8125. * Raise a callback when one of the observable will notify
  8126. * @param observables defines a list of observables to watch
  8127. * @param callback defines the callback to call on notification
  8128. * @param mask defines the mask used to filter notifications
  8129. * @param scope defines the current scope used to restore the JS context
  8130. * @returns the new MultiObserver
  8131. */
  8132. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8133. if (mask === void 0) { mask = -1; }
  8134. if (scope === void 0) { scope = null; }
  8135. var result = new MultiObserver();
  8136. result._observers = new Array();
  8137. result._observables = observables;
  8138. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8139. var observable = observables_1[_i];
  8140. var observer = observable.add(callback, mask, false, scope);
  8141. if (observer) {
  8142. result._observers.push(observer);
  8143. }
  8144. }
  8145. return result;
  8146. };
  8147. return MultiObserver;
  8148. }());
  8149. BABYLON.MultiObserver = MultiObserver;
  8150. /**
  8151. * The Observable class is a simple implementation of the Observable pattern.
  8152. *
  8153. * 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.
  8154. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8155. * 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).
  8156. * 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.
  8157. */
  8158. var Observable = /** @class */ (function () {
  8159. /**
  8160. * Creates a new observable
  8161. * @param onObserverAdded defines a callback to call when a new observer is added
  8162. */
  8163. function Observable(onObserverAdded) {
  8164. this._observers = new Array();
  8165. this._eventState = new EventState(0);
  8166. if (onObserverAdded) {
  8167. this._onObserverAdded = onObserverAdded;
  8168. }
  8169. }
  8170. /**
  8171. * Create a new Observer with the specified callback
  8172. * @param callback the callback that will be executed for that Observer
  8173. * @param mask the mask used to filter observers
  8174. * @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.
  8175. * @param scope optional scope for the callback to be called from
  8176. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8177. * @returns the new observer created for the callback
  8178. */
  8179. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8180. if (mask === void 0) { mask = -1; }
  8181. if (insertFirst === void 0) { insertFirst = false; }
  8182. if (scope === void 0) { scope = null; }
  8183. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8184. if (!callback) {
  8185. return null;
  8186. }
  8187. var observer = new Observer(callback, mask, scope);
  8188. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8189. if (insertFirst) {
  8190. this._observers.unshift(observer);
  8191. }
  8192. else {
  8193. this._observers.push(observer);
  8194. }
  8195. if (this._onObserverAdded) {
  8196. this._onObserverAdded(observer);
  8197. }
  8198. return observer;
  8199. };
  8200. /**
  8201. * Create a new Observer with the specified callback and unregisters after the next notification
  8202. * @param callback the callback that will be executed for that Observer
  8203. * @returns the new observer created for the callback
  8204. */
  8205. Observable.prototype.addOnce = function (callback) {
  8206. return this.add(callback, undefined, undefined, undefined, true);
  8207. };
  8208. /**
  8209. * Remove an Observer from the Observable object
  8210. * @param observer the instance of the Observer to remove
  8211. * @returns false if it doesn't belong to this Observable
  8212. */
  8213. Observable.prototype.remove = function (observer) {
  8214. if (!observer) {
  8215. return false;
  8216. }
  8217. var index = this._observers.indexOf(observer);
  8218. if (index !== -1) {
  8219. this._observers.splice(index, 1);
  8220. return true;
  8221. }
  8222. return false;
  8223. };
  8224. /**
  8225. * Remove a callback from the Observable object
  8226. * @param callback the callback to remove
  8227. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8228. * @returns false if it doesn't belong to this Observable
  8229. */
  8230. Observable.prototype.removeCallback = function (callback, scope) {
  8231. for (var index = 0; index < this._observers.length; index++) {
  8232. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8233. this._observers.splice(index, 1);
  8234. return true;
  8235. }
  8236. }
  8237. return false;
  8238. };
  8239. Observable.prototype._deferUnregister = function (observer) {
  8240. var _this = this;
  8241. observer.unregisterOnNextCall = false;
  8242. observer._willBeUnregistered = true;
  8243. BABYLON.Tools.SetImmediate(function () {
  8244. _this.remove(observer);
  8245. });
  8246. };
  8247. /**
  8248. * Notify all Observers by calling their respective callback with the given data
  8249. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8250. * @param eventData defines the data to send to all observers
  8251. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8252. * @param target defines the original target of the state
  8253. * @param currentTarget defines the current target of the state
  8254. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8255. */
  8256. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8257. if (mask === void 0) { mask = -1; }
  8258. if (!this._observers.length) {
  8259. return true;
  8260. }
  8261. var state = this._eventState;
  8262. state.mask = mask;
  8263. state.target = target;
  8264. state.currentTarget = currentTarget;
  8265. state.skipNextObservers = false;
  8266. state.lastReturnValue = eventData;
  8267. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8268. var obs = _a[_i];
  8269. if (obs._willBeUnregistered) {
  8270. continue;
  8271. }
  8272. if (obs.mask & mask) {
  8273. if (obs.scope) {
  8274. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8275. }
  8276. else {
  8277. state.lastReturnValue = obs.callback(eventData, state);
  8278. }
  8279. if (obs.unregisterOnNextCall) {
  8280. this._deferUnregister(obs);
  8281. }
  8282. }
  8283. if (state.skipNextObservers) {
  8284. return false;
  8285. }
  8286. }
  8287. return true;
  8288. };
  8289. /**
  8290. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8291. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8292. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8293. * and it is crucial that all callbacks will be executed.
  8294. * The order of the callbacks is kept, callbacks are not executed parallel.
  8295. *
  8296. * @param eventData The data to be sent to each callback
  8297. * @param mask is used to filter observers defaults to -1
  8298. * @param target defines the callback target (see EventState)
  8299. * @param currentTarget defines he current object in the bubbling phase
  8300. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8301. */
  8302. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8303. var _this = this;
  8304. if (mask === void 0) { mask = -1; }
  8305. // create an empty promise
  8306. var p = Promise.resolve(eventData);
  8307. // no observers? return this promise.
  8308. if (!this._observers.length) {
  8309. return p;
  8310. }
  8311. var state = this._eventState;
  8312. state.mask = mask;
  8313. state.target = target;
  8314. state.currentTarget = currentTarget;
  8315. state.skipNextObservers = false;
  8316. // execute one callback after another (not using Promise.all, the order is important)
  8317. this._observers.forEach(function (obs) {
  8318. if (state.skipNextObservers) {
  8319. return;
  8320. }
  8321. if (obs._willBeUnregistered) {
  8322. return;
  8323. }
  8324. if (obs.mask & mask) {
  8325. if (obs.scope) {
  8326. p = p.then(function (lastReturnedValue) {
  8327. state.lastReturnValue = lastReturnedValue;
  8328. return obs.callback.apply(obs.scope, [eventData, state]);
  8329. });
  8330. }
  8331. else {
  8332. p = p.then(function (lastReturnedValue) {
  8333. state.lastReturnValue = lastReturnedValue;
  8334. return obs.callback(eventData, state);
  8335. });
  8336. }
  8337. if (obs.unregisterOnNextCall) {
  8338. _this._deferUnregister(obs);
  8339. }
  8340. }
  8341. });
  8342. // return the eventData
  8343. return p.then(function () { return eventData; });
  8344. };
  8345. /**
  8346. * Notify a specific observer
  8347. * @param observer defines the observer to notify
  8348. * @param eventData defines the data to be sent to each callback
  8349. * @param mask is used to filter observers defaults to -1
  8350. */
  8351. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8352. if (mask === void 0) { mask = -1; }
  8353. var state = this._eventState;
  8354. state.mask = mask;
  8355. state.skipNextObservers = false;
  8356. observer.callback(eventData, state);
  8357. };
  8358. /**
  8359. * Gets a boolean indicating if the observable has at least one observer
  8360. * @returns true is the Observable has at least one Observer registered
  8361. */
  8362. Observable.prototype.hasObservers = function () {
  8363. return this._observers.length > 0;
  8364. };
  8365. /**
  8366. * Clear the list of observers
  8367. */
  8368. Observable.prototype.clear = function () {
  8369. this._observers = new Array();
  8370. this._onObserverAdded = null;
  8371. };
  8372. /**
  8373. * Clone the current observable
  8374. * @returns a new observable
  8375. */
  8376. Observable.prototype.clone = function () {
  8377. var result = new Observable();
  8378. result._observers = this._observers.slice(0);
  8379. return result;
  8380. };
  8381. /**
  8382. * Does this observable handles observer registered with a given mask
  8383. * @param mask defines the mask to be tested
  8384. * @return whether or not one observer registered with the given mask is handeled
  8385. **/
  8386. Observable.prototype.hasSpecificMask = function (mask) {
  8387. if (mask === void 0) { mask = -1; }
  8388. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8389. var obs = _a[_i];
  8390. if (obs.mask & mask || obs.mask === mask) {
  8391. return true;
  8392. }
  8393. }
  8394. return false;
  8395. };
  8396. return Observable;
  8397. }());
  8398. BABYLON.Observable = Observable;
  8399. })(BABYLON || (BABYLON = {}));
  8400. //# sourceMappingURL=babylon.observable.js.map
  8401. var BABYLON;
  8402. (function (BABYLON) {
  8403. var SmartArray = /** @class */ (function () {
  8404. function SmartArray(capacity) {
  8405. this.length = 0;
  8406. this.data = new Array(capacity);
  8407. this._id = SmartArray._GlobalId++;
  8408. }
  8409. SmartArray.prototype.push = function (value) {
  8410. this.data[this.length++] = value;
  8411. if (this.length > this.data.length) {
  8412. this.data.length *= 2;
  8413. }
  8414. };
  8415. SmartArray.prototype.forEach = function (func) {
  8416. for (var index = 0; index < this.length; index++) {
  8417. func(this.data[index]);
  8418. }
  8419. };
  8420. SmartArray.prototype.sort = function (compareFn) {
  8421. this.data.sort(compareFn);
  8422. };
  8423. SmartArray.prototype.reset = function () {
  8424. this.length = 0;
  8425. };
  8426. SmartArray.prototype.dispose = function () {
  8427. this.reset();
  8428. if (this.data) {
  8429. this.data.length = 0;
  8430. this.data = [];
  8431. }
  8432. };
  8433. SmartArray.prototype.concat = function (array) {
  8434. if (array.length === 0) {
  8435. return;
  8436. }
  8437. if (this.length + array.length > this.data.length) {
  8438. this.data.length = (this.length + array.length) * 2;
  8439. }
  8440. for (var index = 0; index < array.length; index++) {
  8441. this.data[this.length++] = (array.data || array)[index];
  8442. }
  8443. };
  8444. SmartArray.prototype.indexOf = function (value) {
  8445. var position = this.data.indexOf(value);
  8446. if (position >= this.length) {
  8447. return -1;
  8448. }
  8449. return position;
  8450. };
  8451. SmartArray.prototype.contains = function (value) {
  8452. return this.data.indexOf(value) !== -1;
  8453. };
  8454. // Statics
  8455. SmartArray._GlobalId = 0;
  8456. return SmartArray;
  8457. }());
  8458. BABYLON.SmartArray = SmartArray;
  8459. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8460. __extends(SmartArrayNoDuplicate, _super);
  8461. function SmartArrayNoDuplicate() {
  8462. var _this = _super !== null && _super.apply(this, arguments) || this;
  8463. _this._duplicateId = 0;
  8464. return _this;
  8465. }
  8466. SmartArrayNoDuplicate.prototype.push = function (value) {
  8467. _super.prototype.push.call(this, value);
  8468. if (!value.__smartArrayFlags) {
  8469. value.__smartArrayFlags = {};
  8470. }
  8471. value.__smartArrayFlags[this._id] = this._duplicateId;
  8472. };
  8473. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8474. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8475. return false;
  8476. }
  8477. this.push(value);
  8478. return true;
  8479. };
  8480. SmartArrayNoDuplicate.prototype.reset = function () {
  8481. _super.prototype.reset.call(this);
  8482. this._duplicateId++;
  8483. };
  8484. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8485. if (array.length === 0) {
  8486. return;
  8487. }
  8488. if (this.length + array.length > this.data.length) {
  8489. this.data.length = (this.length + array.length) * 2;
  8490. }
  8491. for (var index = 0; index < array.length; index++) {
  8492. var item = (array.data || array)[index];
  8493. this.pushNoDuplicate(item);
  8494. }
  8495. };
  8496. return SmartArrayNoDuplicate;
  8497. }(SmartArray));
  8498. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8499. })(BABYLON || (BABYLON = {}));
  8500. //# sourceMappingURL=babylon.smartArray.js.map
  8501. var BABYLON;
  8502. (function (BABYLON) {
  8503. /** Class used to store color gradient */
  8504. var ColorGradient = /** @class */ (function () {
  8505. function ColorGradient() {
  8506. }
  8507. /**
  8508. * Will get a color picked randomly between color1 and color2.
  8509. * If color2 is undefined then color1 will be used
  8510. * @param result defines the target Color4 to store the result in
  8511. */
  8512. ColorGradient.prototype.getColorToRef = function (result) {
  8513. if (!this.color2) {
  8514. result.copyFrom(this.color1);
  8515. return;
  8516. }
  8517. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8518. };
  8519. return ColorGradient;
  8520. }());
  8521. BABYLON.ColorGradient = ColorGradient;
  8522. /** Class used to store factor gradient */
  8523. var FactorGradient = /** @class */ (function () {
  8524. function FactorGradient() {
  8525. }
  8526. /**
  8527. * Will get a number picked randomly between factor1 and factor2.
  8528. * If factor2 is undefined then factor1 will be used
  8529. * @returns the picked number
  8530. */
  8531. FactorGradient.prototype.getFactor = function () {
  8532. if (this.factor2 === undefined) {
  8533. return this.factor1;
  8534. }
  8535. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8536. };
  8537. return FactorGradient;
  8538. }());
  8539. BABYLON.FactorGradient = FactorGradient;
  8540. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8541. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8542. var LoadFileError = /** @class */ (function (_super) {
  8543. __extends(LoadFileError, _super);
  8544. function LoadFileError(message, request) {
  8545. var _this = _super.call(this, message) || this;
  8546. _this.request = request;
  8547. _this.name = "LoadFileError";
  8548. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8549. return _this;
  8550. }
  8551. // Polyfill for Object.setPrototypeOf if necessary.
  8552. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8553. return LoadFileError;
  8554. }(Error));
  8555. BABYLON.LoadFileError = LoadFileError;
  8556. var RetryStrategy = /** @class */ (function () {
  8557. function RetryStrategy() {
  8558. }
  8559. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8560. if (maxRetries === void 0) { maxRetries = 3; }
  8561. if (baseInterval === void 0) { baseInterval = 500; }
  8562. return function (url, request, retryIndex) {
  8563. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8564. return -1;
  8565. }
  8566. return Math.pow(2, retryIndex) * baseInterval;
  8567. };
  8568. };
  8569. return RetryStrategy;
  8570. }());
  8571. BABYLON.RetryStrategy = RetryStrategy;
  8572. // Screenshots
  8573. var screenshotCanvas;
  8574. var cloneValue = function (source, destinationObject) {
  8575. if (!source)
  8576. return null;
  8577. if (source instanceof BABYLON.Mesh) {
  8578. return null;
  8579. }
  8580. if (source instanceof BABYLON.SubMesh) {
  8581. return source.clone(destinationObject);
  8582. }
  8583. else if (source.clone) {
  8584. return source.clone();
  8585. }
  8586. return null;
  8587. };
  8588. var Tools = /** @class */ (function () {
  8589. function Tools() {
  8590. }
  8591. /**
  8592. * Interpolates between a and b via alpha
  8593. * @param a The lower value (returned when alpha = 0)
  8594. * @param b The upper value (returned when alpha = 1)
  8595. * @param alpha The interpolation-factor
  8596. * @return The mixed value
  8597. */
  8598. Tools.Mix = function (a, b, alpha) {
  8599. return a * (1 - alpha) + b * alpha;
  8600. };
  8601. Tools.Instantiate = function (className) {
  8602. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8603. return Tools.RegisteredExternalClasses[className];
  8604. }
  8605. var arr = className.split(".");
  8606. var fn = (window || this);
  8607. for (var i = 0, len = arr.length; i < len; i++) {
  8608. fn = fn[arr[i]];
  8609. }
  8610. if (typeof fn !== "function") {
  8611. return null;
  8612. }
  8613. return fn;
  8614. };
  8615. /**
  8616. * Provides a slice function that will work even on IE
  8617. * @param data defines the array to slice
  8618. * @param start defines the start of the data (optional)
  8619. * @param end defines the end of the data (optional)
  8620. * @returns the new sliced array
  8621. */
  8622. Tools.Slice = function (data, start, end) {
  8623. if (data.slice) {
  8624. return data.slice(start, end);
  8625. }
  8626. return Array.prototype.slice.call(data, start, end);
  8627. };
  8628. Tools.SetImmediate = function (action) {
  8629. if (window.setImmediate) {
  8630. window.setImmediate(action);
  8631. }
  8632. else {
  8633. setTimeout(action, 1);
  8634. }
  8635. };
  8636. Tools.IsExponentOfTwo = function (value) {
  8637. var count = 1;
  8638. do {
  8639. count *= 2;
  8640. } while (count < value);
  8641. return count === value;
  8642. };
  8643. /**
  8644. * Returns the nearest 32-bit single precision float representation of a Number
  8645. * @param value A Number. If the parameter is of a different type, it will get converted
  8646. * to a number or to NaN if it cannot be converted
  8647. * @returns number
  8648. */
  8649. Tools.FloatRound = function (value) {
  8650. if (Math.fround) {
  8651. return Math.fround(value);
  8652. }
  8653. return (Tools._tmpFloatArray[0] = value);
  8654. };
  8655. /**
  8656. * Find the next highest power of two.
  8657. * @param x Number to start search from.
  8658. * @return Next highest power of two.
  8659. */
  8660. Tools.CeilingPOT = function (x) {
  8661. x--;
  8662. x |= x >> 1;
  8663. x |= x >> 2;
  8664. x |= x >> 4;
  8665. x |= x >> 8;
  8666. x |= x >> 16;
  8667. x++;
  8668. return x;
  8669. };
  8670. /**
  8671. * Find the next lowest power of two.
  8672. * @param x Number to start search from.
  8673. * @return Next lowest power of two.
  8674. */
  8675. Tools.FloorPOT = function (x) {
  8676. x = x | (x >> 1);
  8677. x = x | (x >> 2);
  8678. x = x | (x >> 4);
  8679. x = x | (x >> 8);
  8680. x = x | (x >> 16);
  8681. return x - (x >> 1);
  8682. };
  8683. /**
  8684. * Find the nearest power of two.
  8685. * @param x Number to start search from.
  8686. * @return Next nearest power of two.
  8687. */
  8688. Tools.NearestPOT = function (x) {
  8689. var c = Tools.CeilingPOT(x);
  8690. var f = Tools.FloorPOT(x);
  8691. return (c - x) > (x - f) ? f : c;
  8692. };
  8693. Tools.GetExponentOfTwo = function (value, max, mode) {
  8694. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8695. var pot;
  8696. switch (mode) {
  8697. case BABYLON.Engine.SCALEMODE_FLOOR:
  8698. pot = Tools.FloorPOT(value);
  8699. break;
  8700. case BABYLON.Engine.SCALEMODE_NEAREST:
  8701. pot = Tools.NearestPOT(value);
  8702. break;
  8703. case BABYLON.Engine.SCALEMODE_CEILING:
  8704. default:
  8705. pot = Tools.CeilingPOT(value);
  8706. break;
  8707. }
  8708. return Math.min(pot, max);
  8709. };
  8710. Tools.GetFilename = function (path) {
  8711. var index = path.lastIndexOf("/");
  8712. if (index < 0)
  8713. return path;
  8714. return path.substring(index + 1);
  8715. };
  8716. /**
  8717. * Extracts the "folder" part of a path (everything before the filename).
  8718. * @param uri The URI to extract the info from
  8719. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8720. * @returns The "folder" part of the path
  8721. */
  8722. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8723. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8724. var index = uri.lastIndexOf("/");
  8725. if (index < 0) {
  8726. if (returnUnchangedIfNoSlash) {
  8727. return uri;
  8728. }
  8729. return "";
  8730. }
  8731. return uri.substring(0, index + 1);
  8732. };
  8733. Tools.GetDOMTextContent = function (element) {
  8734. var result = "";
  8735. var child = element.firstChild;
  8736. while (child) {
  8737. if (child.nodeType === 3) {
  8738. result += child.textContent;
  8739. }
  8740. child = child.nextSibling;
  8741. }
  8742. return result;
  8743. };
  8744. Tools.ToDegrees = function (angle) {
  8745. return angle * 180 / Math.PI;
  8746. };
  8747. Tools.ToRadians = function (angle) {
  8748. return angle * Math.PI / 180;
  8749. };
  8750. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8751. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8752. var output = "";
  8753. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8754. var i = 0;
  8755. var bytes = new Uint8Array(buffer);
  8756. while (i < bytes.length) {
  8757. chr1 = bytes[i++];
  8758. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8759. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8760. enc1 = chr1 >> 2;
  8761. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8762. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8763. enc4 = chr3 & 63;
  8764. if (isNaN(chr2)) {
  8765. enc3 = enc4 = 64;
  8766. }
  8767. else if (isNaN(chr3)) {
  8768. enc4 = 64;
  8769. }
  8770. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8771. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8772. }
  8773. return "data:image/png;base64," + output;
  8774. };
  8775. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8776. if (bias === void 0) { bias = null; }
  8777. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8778. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8779. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8780. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8781. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8782. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8783. }
  8784. if (bias) {
  8785. minimum.x -= minimum.x * bias.x + bias.y;
  8786. minimum.y -= minimum.y * bias.x + bias.y;
  8787. minimum.z -= minimum.z * bias.x + bias.y;
  8788. maximum.x += maximum.x * bias.x + bias.y;
  8789. maximum.y += maximum.y * bias.x + bias.y;
  8790. maximum.z += maximum.z * bias.x + bias.y;
  8791. }
  8792. return {
  8793. minimum: minimum,
  8794. maximum: maximum
  8795. };
  8796. };
  8797. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8798. if (bias === void 0) { bias = null; }
  8799. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8800. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8801. if (!stride) {
  8802. stride = 3;
  8803. }
  8804. for (var index = start; index < start + count; index++) {
  8805. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8806. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8807. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8808. }
  8809. if (bias) {
  8810. minimum.x -= minimum.x * bias.x + bias.y;
  8811. minimum.y -= minimum.y * bias.x + bias.y;
  8812. minimum.z -= minimum.z * bias.x + bias.y;
  8813. maximum.x += maximum.x * bias.x + bias.y;
  8814. maximum.y += maximum.y * bias.x + bias.y;
  8815. maximum.z += maximum.z * bias.x + bias.y;
  8816. }
  8817. return {
  8818. minimum: minimum,
  8819. maximum: maximum
  8820. };
  8821. };
  8822. Tools.Vector2ArrayFeeder = function (array) {
  8823. return function (index) {
  8824. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8825. var length = isFloatArray ? array.length / 2 : array.length;
  8826. if (index >= length) {
  8827. return null;
  8828. }
  8829. if (isFloatArray) {
  8830. var fa = array;
  8831. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8832. }
  8833. var a = array;
  8834. return a[index];
  8835. };
  8836. };
  8837. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8838. if (bias === void 0) { bias = null; }
  8839. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8840. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8841. var i = 0;
  8842. var cur = feeder(i++);
  8843. while (cur) {
  8844. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8845. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8846. cur = feeder(i++);
  8847. }
  8848. if (bias) {
  8849. minimum.x -= minimum.x * bias.x + bias.y;
  8850. minimum.y -= minimum.y * bias.x + bias.y;
  8851. maximum.x += maximum.x * bias.x + bias.y;
  8852. maximum.y += maximum.y * bias.x + bias.y;
  8853. }
  8854. return {
  8855. minimum: minimum,
  8856. maximum: maximum
  8857. };
  8858. };
  8859. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8860. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8861. return null;
  8862. return Array.isArray(obj) ? obj : [obj];
  8863. };
  8864. // Misc.
  8865. Tools.GetPointerPrefix = function () {
  8866. var eventPrefix = "pointer";
  8867. // Check if pointer events are supported
  8868. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8869. eventPrefix = "mouse";
  8870. }
  8871. return eventPrefix;
  8872. };
  8873. /**
  8874. * @param func - the function to be called
  8875. * @param requester - the object that will request the next frame. Falls back to window.
  8876. */
  8877. Tools.QueueNewFrame = function (func, requester) {
  8878. if (!Tools.IsWindowObjectExist()) {
  8879. return setTimeout(func, 16);
  8880. }
  8881. if (!requester) {
  8882. requester = window;
  8883. }
  8884. if (requester.requestAnimationFrame) {
  8885. return requester.requestAnimationFrame(func);
  8886. }
  8887. else if (requester.msRequestAnimationFrame) {
  8888. return requester.msRequestAnimationFrame(func);
  8889. }
  8890. else if (requester.webkitRequestAnimationFrame) {
  8891. return requester.webkitRequestAnimationFrame(func);
  8892. }
  8893. else if (requester.mozRequestAnimationFrame) {
  8894. return requester.mozRequestAnimationFrame(func);
  8895. }
  8896. else if (requester.oRequestAnimationFrame) {
  8897. return requester.oRequestAnimationFrame(func);
  8898. }
  8899. else {
  8900. return window.setTimeout(func, 16);
  8901. }
  8902. };
  8903. Tools.RequestFullscreen = function (element) {
  8904. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8905. if (!requestFunction)
  8906. return;
  8907. requestFunction.call(element);
  8908. };
  8909. Tools.ExitFullscreen = function () {
  8910. if (document.exitFullscreen) {
  8911. document.exitFullscreen();
  8912. }
  8913. else if (document.mozCancelFullScreen) {
  8914. document.mozCancelFullScreen();
  8915. }
  8916. else if (document.webkitCancelFullScreen) {
  8917. document.webkitCancelFullScreen();
  8918. }
  8919. else if (document.msCancelFullScreen) {
  8920. document.msCancelFullScreen();
  8921. }
  8922. };
  8923. Tools.SetCorsBehavior = function (url, element) {
  8924. if (url && url.indexOf("data:") === 0) {
  8925. return;
  8926. }
  8927. if (Tools.CorsBehavior) {
  8928. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8929. element.crossOrigin = Tools.CorsBehavior;
  8930. }
  8931. else {
  8932. var result = Tools.CorsBehavior(url);
  8933. if (result) {
  8934. element.crossOrigin = result;
  8935. }
  8936. }
  8937. }
  8938. };
  8939. // External files
  8940. Tools.CleanUrl = function (url) {
  8941. url = url.replace(/#/mg, "%23");
  8942. return url;
  8943. };
  8944. /**
  8945. * Loads an image as an HTMLImageElement.
  8946. * @param input url string, ArrayBuffer, or Blob to load
  8947. * @param onLoad callback called when the image successfully loads
  8948. * @param onError callback called when the image fails to load
  8949. * @param database database for caching
  8950. * @returns the HTMLImageElement of the loaded image
  8951. */
  8952. Tools.LoadImage = function (input, onLoad, onError, database) {
  8953. var url;
  8954. var usingObjectURL = false;
  8955. if (input instanceof ArrayBuffer) {
  8956. url = URL.createObjectURL(new Blob([input]));
  8957. usingObjectURL = true;
  8958. }
  8959. else if (input instanceof Blob) {
  8960. url = URL.createObjectURL(input);
  8961. usingObjectURL = true;
  8962. }
  8963. else {
  8964. url = Tools.CleanUrl(input);
  8965. url = Tools.PreprocessUrl(input);
  8966. }
  8967. var img = new Image();
  8968. Tools.SetCorsBehavior(url, img);
  8969. var loadHandler = function () {
  8970. if (usingObjectURL && img.src) {
  8971. URL.revokeObjectURL(img.src);
  8972. }
  8973. img.removeEventListener("load", loadHandler);
  8974. img.removeEventListener("error", errorHandler);
  8975. onLoad(img);
  8976. };
  8977. var errorHandler = function (err) {
  8978. if (usingObjectURL && img.src) {
  8979. URL.revokeObjectURL(img.src);
  8980. }
  8981. img.removeEventListener("load", loadHandler);
  8982. img.removeEventListener("error", errorHandler);
  8983. Tools.Error("Error while trying to load image: " + input);
  8984. if (onError) {
  8985. onError("Error while trying to load image: " + input, err);
  8986. }
  8987. };
  8988. img.addEventListener("load", loadHandler);
  8989. img.addEventListener("error", errorHandler);
  8990. var noIndexedDB = function () {
  8991. img.src = url;
  8992. };
  8993. var loadFromIndexedDB = function () {
  8994. if (database) {
  8995. database.loadImageFromDB(url, img);
  8996. }
  8997. };
  8998. //ANY database to do!
  8999. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9000. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9001. }
  9002. else {
  9003. if (url.indexOf("file:") !== -1) {
  9004. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9005. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9006. try {
  9007. var blobURL;
  9008. try {
  9009. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9010. }
  9011. catch (ex) {
  9012. // Chrome doesn't support oneTimeOnly parameter
  9013. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9014. }
  9015. img.src = blobURL;
  9016. usingObjectURL = true;
  9017. }
  9018. catch (e) {
  9019. img.src = "";
  9020. }
  9021. return img;
  9022. }
  9023. }
  9024. noIndexedDB();
  9025. }
  9026. return img;
  9027. };
  9028. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9029. url = Tools.CleanUrl(url);
  9030. url = Tools.PreprocessUrl(url);
  9031. // If file and file input are set
  9032. if (url.indexOf("file:") !== -1) {
  9033. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9034. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9035. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9036. }
  9037. }
  9038. var loadUrl = Tools.BaseUrl + url;
  9039. var aborted = false;
  9040. var fileRequest = {
  9041. onCompleteObservable: new BABYLON.Observable(),
  9042. abort: function () { return aborted = true; },
  9043. };
  9044. var requestFile = function () {
  9045. var request = new XMLHttpRequest();
  9046. var retryHandle = null;
  9047. fileRequest.abort = function () {
  9048. aborted = true;
  9049. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9050. request.abort();
  9051. }
  9052. if (retryHandle !== null) {
  9053. clearTimeout(retryHandle);
  9054. retryHandle = null;
  9055. }
  9056. };
  9057. var retryLoop = function (retryIndex) {
  9058. request.open('GET', loadUrl, true);
  9059. if (useArrayBuffer) {
  9060. request.responseType = "arraybuffer";
  9061. }
  9062. if (onProgress) {
  9063. request.addEventListener("progress", onProgress);
  9064. }
  9065. var onLoadEnd = function () {
  9066. request.removeEventListener("loadend", onLoadEnd);
  9067. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9068. fileRequest.onCompleteObservable.clear();
  9069. };
  9070. request.addEventListener("loadend", onLoadEnd);
  9071. var onReadyStateChange = function () {
  9072. if (aborted) {
  9073. return;
  9074. }
  9075. // In case of undefined state in some browsers.
  9076. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9077. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9078. request.removeEventListener("readystatechange", onReadyStateChange);
  9079. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9080. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9081. return;
  9082. }
  9083. var retryStrategy = Tools.DefaultRetryStrategy;
  9084. if (retryStrategy) {
  9085. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9086. if (waitTime !== -1) {
  9087. // Prevent the request from completing for retry.
  9088. request.removeEventListener("loadend", onLoadEnd);
  9089. request = new XMLHttpRequest();
  9090. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9091. return;
  9092. }
  9093. }
  9094. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9095. if (onError) {
  9096. onError(request, e);
  9097. }
  9098. else {
  9099. throw e;
  9100. }
  9101. }
  9102. };
  9103. request.addEventListener("readystatechange", onReadyStateChange);
  9104. request.send();
  9105. };
  9106. retryLoop(0);
  9107. };
  9108. // Caching all files
  9109. if (database && database.enableSceneOffline) {
  9110. var noIndexedDB_1 = function () {
  9111. if (!aborted) {
  9112. requestFile();
  9113. }
  9114. };
  9115. var loadFromIndexedDB = function () {
  9116. // TODO: database needs to support aborting and should return a IFileRequest
  9117. if (aborted) {
  9118. return;
  9119. }
  9120. if (database) {
  9121. database.loadFileFromDB(url, function (data) {
  9122. if (!aborted) {
  9123. onSuccess(data);
  9124. }
  9125. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9126. }, onProgress ? function (event) {
  9127. if (!aborted) {
  9128. onProgress(event);
  9129. }
  9130. } : undefined, noIndexedDB_1, useArrayBuffer);
  9131. }
  9132. };
  9133. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9134. }
  9135. else {
  9136. requestFile();
  9137. }
  9138. return fileRequest;
  9139. };
  9140. /**
  9141. * Load a script (identified by an url). When the url returns, the
  9142. * content of this file is added into a new script element, attached to the DOM (body element)
  9143. */
  9144. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9145. var head = document.getElementsByTagName('head')[0];
  9146. var script = document.createElement('script');
  9147. script.type = 'text/javascript';
  9148. script.src = scriptUrl;
  9149. script.onload = function () {
  9150. if (onSuccess) {
  9151. onSuccess();
  9152. }
  9153. };
  9154. script.onerror = function (e) {
  9155. if (onError) {
  9156. onError("Unable to load script '" + scriptUrl + "'", e);
  9157. }
  9158. };
  9159. head.appendChild(script);
  9160. };
  9161. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9162. var reader = new FileReader();
  9163. var request = {
  9164. onCompleteObservable: new BABYLON.Observable(),
  9165. abort: function () { return reader.abort(); },
  9166. };
  9167. reader.onloadend = function (e) {
  9168. request.onCompleteObservable.notifyObservers(request);
  9169. };
  9170. reader.onload = function (e) {
  9171. //target doesn't have result from ts 1.3
  9172. callback(e.target['result']);
  9173. };
  9174. reader.onprogress = progressCallback;
  9175. reader.readAsDataURL(fileToLoad);
  9176. return request;
  9177. };
  9178. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9179. var reader = new FileReader();
  9180. var request = {
  9181. onCompleteObservable: new BABYLON.Observable(),
  9182. abort: function () { return reader.abort(); },
  9183. };
  9184. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9185. reader.onerror = function (e) {
  9186. Tools.Log("Error while reading file: " + fileToLoad.name);
  9187. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9188. };
  9189. reader.onload = function (e) {
  9190. //target doesn't have result from ts 1.3
  9191. callback(e.target['result']);
  9192. };
  9193. if (progressCallBack) {
  9194. reader.onprogress = progressCallBack;
  9195. }
  9196. if (!useArrayBuffer) {
  9197. // Asynchronous read
  9198. reader.readAsText(fileToLoad);
  9199. }
  9200. else {
  9201. reader.readAsArrayBuffer(fileToLoad);
  9202. }
  9203. return request;
  9204. };
  9205. //returns a downloadable url to a file content.
  9206. Tools.FileAsURL = function (content) {
  9207. var fileBlob = new Blob([content]);
  9208. var url = window.URL || window.webkitURL;
  9209. var link = url.createObjectURL(fileBlob);
  9210. return link;
  9211. };
  9212. // Misc.
  9213. Tools.Format = function (value, decimals) {
  9214. if (decimals === void 0) { decimals = 2; }
  9215. return value.toFixed(decimals);
  9216. };
  9217. Tools.CheckExtends = function (v, min, max) {
  9218. if (v.x < min.x)
  9219. min.x = v.x;
  9220. if (v.y < min.y)
  9221. min.y = v.y;
  9222. if (v.z < min.z)
  9223. min.z = v.z;
  9224. if (v.x > max.x)
  9225. max.x = v.x;
  9226. if (v.y > max.y)
  9227. max.y = v.y;
  9228. if (v.z > max.z)
  9229. max.z = v.z;
  9230. };
  9231. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9232. for (var prop in source) {
  9233. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9234. continue;
  9235. }
  9236. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9237. continue;
  9238. }
  9239. var sourceValue = source[prop];
  9240. var typeOfSourceValue = typeof sourceValue;
  9241. if (typeOfSourceValue === "function") {
  9242. continue;
  9243. }
  9244. try {
  9245. if (typeOfSourceValue === "object") {
  9246. if (sourceValue instanceof Array) {
  9247. destination[prop] = [];
  9248. if (sourceValue.length > 0) {
  9249. if (typeof sourceValue[0] == "object") {
  9250. for (var index = 0; index < sourceValue.length; index++) {
  9251. var clonedValue = cloneValue(sourceValue[index], destination);
  9252. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9253. destination[prop].push(clonedValue);
  9254. }
  9255. }
  9256. }
  9257. else {
  9258. destination[prop] = sourceValue.slice(0);
  9259. }
  9260. }
  9261. }
  9262. else {
  9263. destination[prop] = cloneValue(sourceValue, destination);
  9264. }
  9265. }
  9266. else {
  9267. destination[prop] = sourceValue;
  9268. }
  9269. }
  9270. catch (e) {
  9271. // Just ignore error (it could be because of a read-only property)
  9272. }
  9273. }
  9274. };
  9275. Tools.IsEmpty = function (obj) {
  9276. for (var i in obj) {
  9277. if (obj.hasOwnProperty(i)) {
  9278. return false;
  9279. }
  9280. }
  9281. return true;
  9282. };
  9283. Tools.RegisterTopRootEvents = function (events) {
  9284. for (var index = 0; index < events.length; index++) {
  9285. var event = events[index];
  9286. window.addEventListener(event.name, event.handler, false);
  9287. try {
  9288. if (window.parent) {
  9289. window.parent.addEventListener(event.name, event.handler, false);
  9290. }
  9291. }
  9292. catch (e) {
  9293. // Silently fails...
  9294. }
  9295. }
  9296. };
  9297. Tools.UnregisterTopRootEvents = function (events) {
  9298. for (var index = 0; index < events.length; index++) {
  9299. var event = events[index];
  9300. window.removeEventListener(event.name, event.handler);
  9301. try {
  9302. if (window.parent) {
  9303. window.parent.removeEventListener(event.name, event.handler);
  9304. }
  9305. }
  9306. catch (e) {
  9307. // Silently fails...
  9308. }
  9309. }
  9310. };
  9311. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9312. if (mimeType === void 0) { mimeType = "image/png"; }
  9313. // Read the contents of the framebuffer
  9314. var numberOfChannelsByLine = width * 4;
  9315. var halfHeight = height / 2;
  9316. //Reading datas from WebGL
  9317. var data = engine.readPixels(0, 0, width, height);
  9318. //To flip image on Y axis.
  9319. for (var i = 0; i < halfHeight; i++) {
  9320. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9321. var currentCell = j + i * numberOfChannelsByLine;
  9322. var targetLine = height - i - 1;
  9323. var targetCell = j + targetLine * numberOfChannelsByLine;
  9324. var temp = data[currentCell];
  9325. data[currentCell] = data[targetCell];
  9326. data[targetCell] = temp;
  9327. }
  9328. }
  9329. // Create a 2D canvas to store the result
  9330. if (!screenshotCanvas) {
  9331. screenshotCanvas = document.createElement('canvas');
  9332. }
  9333. screenshotCanvas.width = width;
  9334. screenshotCanvas.height = height;
  9335. var context = screenshotCanvas.getContext('2d');
  9336. if (context) {
  9337. // Copy the pixels to a 2D canvas
  9338. var imageData = context.createImageData(width, height);
  9339. var castData = (imageData.data);
  9340. castData.set(data);
  9341. context.putImageData(imageData, 0, 0);
  9342. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9343. }
  9344. };
  9345. /**
  9346. * Converts the canvas data to blob.
  9347. * This acts as a polyfill for browsers not supporting the to blob function.
  9348. * @param canvas Defines the canvas to extract the data from
  9349. * @param successCallback Defines the callback triggered once the data are available
  9350. * @param mimeType Defines the mime type of the result
  9351. */
  9352. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9353. if (mimeType === void 0) { mimeType = "image/png"; }
  9354. // We need HTMLCanvasElement.toBlob for HD screenshots
  9355. if (!canvas.toBlob) {
  9356. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9357. canvas.toBlob = function (callback, type, quality) {
  9358. var _this = this;
  9359. setTimeout(function () {
  9360. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9361. for (var i = 0; i < len; i++) {
  9362. arr[i] = binStr.charCodeAt(i);
  9363. }
  9364. callback(new Blob([arr]));
  9365. });
  9366. };
  9367. }
  9368. canvas.toBlob(function (blob) {
  9369. successCallback(blob);
  9370. }, mimeType);
  9371. };
  9372. /**
  9373. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9374. * @param successCallback Defines the callback triggered once the data are available
  9375. * @param mimeType Defines the mime type of the result
  9376. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9377. */
  9378. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9379. if (mimeType === void 0) { mimeType = "image/png"; }
  9380. if (successCallback) {
  9381. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9382. successCallback(base64Image);
  9383. }
  9384. else {
  9385. this.ToBlob(screenshotCanvas, function (blob) {
  9386. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9387. if (("download" in document.createElement("a"))) {
  9388. if (!fileName) {
  9389. var date = new Date();
  9390. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9391. fileName = "screenshot_" + stringDate + ".png";
  9392. }
  9393. Tools.Download(blob, fileName);
  9394. }
  9395. else {
  9396. var url = URL.createObjectURL(blob);
  9397. var newWindow = window.open("");
  9398. if (!newWindow)
  9399. return;
  9400. var img = newWindow.document.createElement("img");
  9401. img.onload = function () {
  9402. // no longer need to read the blob so it's revoked
  9403. URL.revokeObjectURL(url);
  9404. };
  9405. img.src = url;
  9406. newWindow.document.body.appendChild(img);
  9407. }
  9408. }, mimeType);
  9409. }
  9410. };
  9411. /**
  9412. * Downloads a blob in the browser
  9413. * @param blob defines the blob to download
  9414. * @param fileName defines the name of the downloaded file
  9415. */
  9416. Tools.Download = function (blob, fileName) {
  9417. var url = window.URL.createObjectURL(blob);
  9418. var a = document.createElement("a");
  9419. document.body.appendChild(a);
  9420. a.style.display = "none";
  9421. a.href = url;
  9422. a.download = fileName;
  9423. a.addEventListener("click", function () {
  9424. if (a.parentElement) {
  9425. a.parentElement.removeChild(a);
  9426. }
  9427. });
  9428. a.click();
  9429. window.URL.revokeObjectURL(url);
  9430. };
  9431. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9432. if (mimeType === void 0) { mimeType = "image/png"; }
  9433. var width;
  9434. var height;
  9435. // If a precision value is specified
  9436. if (size.precision) {
  9437. width = Math.round(engine.getRenderWidth() * size.precision);
  9438. height = Math.round(width / engine.getAspectRatio(camera));
  9439. }
  9440. else if (size.width && size.height) {
  9441. width = size.width;
  9442. height = size.height;
  9443. }
  9444. //If passing only width, computing height to keep display canvas ratio.
  9445. else if (size.width && !size.height) {
  9446. width = size.width;
  9447. height = Math.round(width / engine.getAspectRatio(camera));
  9448. }
  9449. //If passing only height, computing width to keep display canvas ratio.
  9450. else if (size.height && !size.width) {
  9451. height = size.height;
  9452. width = Math.round(height * engine.getAspectRatio(camera));
  9453. }
  9454. //Assuming here that "size" parameter is a number
  9455. else if (!isNaN(size)) {
  9456. height = size;
  9457. width = size;
  9458. }
  9459. else {
  9460. Tools.Error("Invalid 'size' parameter !");
  9461. return;
  9462. }
  9463. if (!screenshotCanvas) {
  9464. screenshotCanvas = document.createElement('canvas');
  9465. }
  9466. screenshotCanvas.width = width;
  9467. screenshotCanvas.height = height;
  9468. var renderContext = screenshotCanvas.getContext("2d");
  9469. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9470. var newWidth = width;
  9471. var newHeight = newWidth / ratio;
  9472. if (newHeight > height) {
  9473. newHeight = height;
  9474. newWidth = newHeight * ratio;
  9475. }
  9476. var offsetX = Math.max(0, width - newWidth) / 2;
  9477. var offsetY = Math.max(0, height - newHeight) / 2;
  9478. var renderingCanvas = engine.getRenderingCanvas();
  9479. if (renderContext && renderingCanvas) {
  9480. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9481. }
  9482. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9483. };
  9484. /**
  9485. * Generates an image screenshot from the specified camera.
  9486. *
  9487. * @param engine The engine to use for rendering
  9488. * @param camera The camera to use for rendering
  9489. * @param size This parameter can be set to a single number or to an object with the
  9490. * following (optional) properties: precision, width, height. If a single number is passed,
  9491. * it will be used for both width and height. If an object is passed, the screenshot size
  9492. * will be derived from the parameters. The precision property is a multiplier allowing
  9493. * rendering at a higher or lower resolution.
  9494. * @param successCallback The callback receives a single parameter which contains the
  9495. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9496. * src parameter of an <img> to display it.
  9497. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9498. * Check your browser for supported MIME types.
  9499. * @param samples Texture samples (default: 1)
  9500. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9501. * @param fileName A name for for the downloaded file.
  9502. * @constructor
  9503. */
  9504. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9505. if (mimeType === void 0) { mimeType = "image/png"; }
  9506. if (samples === void 0) { samples = 1; }
  9507. if (antialiasing === void 0) { antialiasing = false; }
  9508. var width;
  9509. var height;
  9510. //If a precision value is specified
  9511. if (size.precision) {
  9512. width = Math.round(engine.getRenderWidth() * size.precision);
  9513. height = Math.round(width / engine.getAspectRatio(camera));
  9514. size = { width: width, height: height };
  9515. }
  9516. else if (size.width && size.height) {
  9517. width = size.width;
  9518. height = size.height;
  9519. }
  9520. //If passing only width, computing height to keep display canvas ratio.
  9521. else if (size.width && !size.height) {
  9522. width = size.width;
  9523. height = Math.round(width / engine.getAspectRatio(camera));
  9524. size = { width: width, height: height };
  9525. }
  9526. //If passing only height, computing width to keep display canvas ratio.
  9527. else if (size.height && !size.width) {
  9528. height = size.height;
  9529. width = Math.round(height * engine.getAspectRatio(camera));
  9530. size = { width: width, height: height };
  9531. }
  9532. //Assuming here that "size" parameter is a number
  9533. else if (!isNaN(size)) {
  9534. height = size;
  9535. width = size;
  9536. }
  9537. else {
  9538. Tools.Error("Invalid 'size' parameter !");
  9539. return;
  9540. }
  9541. var scene = camera.getScene();
  9542. var previousCamera = null;
  9543. if (scene.activeCamera !== camera) {
  9544. previousCamera = scene.activeCamera;
  9545. scene.activeCamera = camera;
  9546. }
  9547. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9548. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9549. texture.renderList = null;
  9550. texture.samples = samples;
  9551. if (antialiasing) {
  9552. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9553. }
  9554. texture.onAfterRenderObservable.add(function () {
  9555. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9556. });
  9557. scene.incrementRenderId();
  9558. scene.resetCachedMaterial();
  9559. texture.render(true);
  9560. texture.dispose();
  9561. if (previousCamera) {
  9562. scene.activeCamera = previousCamera;
  9563. }
  9564. camera.getProjectionMatrix(true); // Force cache refresh;
  9565. };
  9566. // XHR response validator for local file scenario
  9567. Tools.ValidateXHRData = function (xhr, dataType) {
  9568. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9569. if (dataType === void 0) { dataType = 7; }
  9570. try {
  9571. if (dataType & 1) {
  9572. if (xhr.responseText && xhr.responseText.length > 0) {
  9573. return true;
  9574. }
  9575. else if (dataType === 1) {
  9576. return false;
  9577. }
  9578. }
  9579. if (dataType & 2) {
  9580. // Check header width and height since there is no "TGA" magic number
  9581. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9582. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9583. return true;
  9584. }
  9585. else if (dataType === 2) {
  9586. return false;
  9587. }
  9588. }
  9589. if (dataType & 4) {
  9590. // Check for the "DDS" magic number
  9591. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9592. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9593. return true;
  9594. }
  9595. else {
  9596. return false;
  9597. }
  9598. }
  9599. }
  9600. catch (e) {
  9601. // Global protection
  9602. }
  9603. return false;
  9604. };
  9605. /**
  9606. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9607. * Be aware Math.random() could cause collisions, but:
  9608. * "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"
  9609. */
  9610. Tools.RandomId = function () {
  9611. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9612. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9613. return v.toString(16);
  9614. });
  9615. };
  9616. /**
  9617. * Test if the given uri is a base64 string.
  9618. * @param uri The uri to test
  9619. * @return True if the uri is a base64 string or false otherwise.
  9620. */
  9621. Tools.IsBase64 = function (uri) {
  9622. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9623. };
  9624. /**
  9625. * Decode the given base64 uri.
  9626. * @param uri The uri to decode
  9627. * @return The decoded base64 data.
  9628. */
  9629. Tools.DecodeBase64 = function (uri) {
  9630. var decodedString = atob(uri.split(",")[1]);
  9631. var bufferLength = decodedString.length;
  9632. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9633. for (var i = 0; i < bufferLength; i++) {
  9634. bufferView[i] = decodedString.charCodeAt(i);
  9635. }
  9636. return bufferView.buffer;
  9637. };
  9638. Object.defineProperty(Tools, "NoneLogLevel", {
  9639. get: function () {
  9640. return Tools._NoneLogLevel;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Tools, "MessageLogLevel", {
  9646. get: function () {
  9647. return Tools._MessageLogLevel;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Tools, "WarningLogLevel", {
  9653. get: function () {
  9654. return Tools._WarningLogLevel;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(Tools, "ErrorLogLevel", {
  9660. get: function () {
  9661. return Tools._ErrorLogLevel;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Object.defineProperty(Tools, "AllLogLevel", {
  9667. get: function () {
  9668. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9669. },
  9670. enumerable: true,
  9671. configurable: true
  9672. });
  9673. Tools._AddLogEntry = function (entry) {
  9674. Tools._LogCache = entry + Tools._LogCache;
  9675. if (Tools.OnNewCacheEntry) {
  9676. Tools.OnNewCacheEntry(entry);
  9677. }
  9678. };
  9679. Tools._FormatMessage = function (message) {
  9680. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9681. var date = new Date();
  9682. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9683. };
  9684. Tools._LogDisabled = function (message) {
  9685. // nothing to do
  9686. };
  9687. Tools._LogEnabled = function (message) {
  9688. var formattedMessage = Tools._FormatMessage(message);
  9689. console.log("BJS - " + formattedMessage);
  9690. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9691. Tools._AddLogEntry(entry);
  9692. };
  9693. Tools._WarnDisabled = function (message) {
  9694. // nothing to do
  9695. };
  9696. Tools._WarnEnabled = function (message) {
  9697. var formattedMessage = Tools._FormatMessage(message);
  9698. console.warn("BJS - " + formattedMessage);
  9699. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9700. Tools._AddLogEntry(entry);
  9701. };
  9702. Tools._ErrorDisabled = function (message) {
  9703. // nothing to do
  9704. };
  9705. Tools._ErrorEnabled = function (message) {
  9706. Tools.errorsCount++;
  9707. var formattedMessage = Tools._FormatMessage(message);
  9708. console.error("BJS - " + formattedMessage);
  9709. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9710. Tools._AddLogEntry(entry);
  9711. };
  9712. Object.defineProperty(Tools, "LogCache", {
  9713. get: function () {
  9714. return Tools._LogCache;
  9715. },
  9716. enumerable: true,
  9717. configurable: true
  9718. });
  9719. Tools.ClearLogCache = function () {
  9720. Tools._LogCache = "";
  9721. Tools.errorsCount = 0;
  9722. };
  9723. Object.defineProperty(Tools, "LogLevels", {
  9724. set: function (level) {
  9725. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9726. Tools.Log = Tools._LogEnabled;
  9727. }
  9728. else {
  9729. Tools.Log = Tools._LogDisabled;
  9730. }
  9731. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9732. Tools.Warn = Tools._WarnEnabled;
  9733. }
  9734. else {
  9735. Tools.Warn = Tools._WarnDisabled;
  9736. }
  9737. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9738. Tools.Error = Tools._ErrorEnabled;
  9739. }
  9740. else {
  9741. Tools.Error = Tools._ErrorDisabled;
  9742. }
  9743. },
  9744. enumerable: true,
  9745. configurable: true
  9746. });
  9747. Tools.IsWindowObjectExist = function () {
  9748. return (typeof window) !== "undefined";
  9749. };
  9750. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9751. get: function () {
  9752. return Tools._PerformanceNoneLogLevel;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9758. get: function () {
  9759. return Tools._PerformanceUserMarkLogLevel;
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9765. get: function () {
  9766. return Tools._PerformanceConsoleLogLevel;
  9767. },
  9768. enumerable: true,
  9769. configurable: true
  9770. });
  9771. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9772. set: function (level) {
  9773. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9774. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9775. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9776. return;
  9777. }
  9778. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9779. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9780. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9781. return;
  9782. }
  9783. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9784. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9785. },
  9786. enumerable: true,
  9787. configurable: true
  9788. });
  9789. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9790. };
  9791. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9792. };
  9793. Tools._StartUserMark = function (counterName, condition) {
  9794. if (condition === void 0) { condition = true; }
  9795. if (!Tools._performance) {
  9796. if (!Tools.IsWindowObjectExist()) {
  9797. return;
  9798. }
  9799. Tools._performance = window.performance;
  9800. }
  9801. if (!condition || !Tools._performance.mark) {
  9802. return;
  9803. }
  9804. Tools._performance.mark(counterName + "-Begin");
  9805. };
  9806. Tools._EndUserMark = function (counterName, condition) {
  9807. if (condition === void 0) { condition = true; }
  9808. if (!condition || !Tools._performance.mark) {
  9809. return;
  9810. }
  9811. Tools._performance.mark(counterName + "-End");
  9812. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9813. };
  9814. Tools._StartPerformanceConsole = function (counterName, condition) {
  9815. if (condition === void 0) { condition = true; }
  9816. if (!condition) {
  9817. return;
  9818. }
  9819. Tools._StartUserMark(counterName, condition);
  9820. if (console.time) {
  9821. console.time(counterName);
  9822. }
  9823. };
  9824. Tools._EndPerformanceConsole = function (counterName, condition) {
  9825. if (condition === void 0) { condition = true; }
  9826. if (!condition) {
  9827. return;
  9828. }
  9829. Tools._EndUserMark(counterName, condition);
  9830. if (console.time) {
  9831. console.timeEnd(counterName);
  9832. }
  9833. };
  9834. Object.defineProperty(Tools, "Now", {
  9835. get: function () {
  9836. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9837. return window.performance.now();
  9838. }
  9839. return Date.now();
  9840. },
  9841. enumerable: true,
  9842. configurable: true
  9843. });
  9844. /**
  9845. * This method will return the name of the class used to create the instance of the given object.
  9846. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9847. * @param object the object to get the class name from
  9848. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9849. */
  9850. Tools.GetClassName = function (object, isType) {
  9851. if (isType === void 0) { isType = false; }
  9852. var name = null;
  9853. if (!isType && object.getClassName) {
  9854. name = object.getClassName();
  9855. }
  9856. else {
  9857. if (object instanceof Object) {
  9858. var classObj = isType ? object : Object.getPrototypeOf(object);
  9859. name = classObj.constructor["__bjsclassName__"];
  9860. }
  9861. if (!name) {
  9862. name = typeof object;
  9863. }
  9864. }
  9865. return name;
  9866. };
  9867. Tools.First = function (array, predicate) {
  9868. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9869. var el = array_1[_i];
  9870. if (predicate(el)) {
  9871. return el;
  9872. }
  9873. }
  9874. return null;
  9875. };
  9876. /**
  9877. * This method will return the name of the full name of the class, including its owning module (if any).
  9878. * 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).
  9879. * @param object the object to get the class name from
  9880. * @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.
  9881. */
  9882. Tools.getFullClassName = function (object, isType) {
  9883. if (isType === void 0) { isType = false; }
  9884. var className = null;
  9885. var moduleName = null;
  9886. if (!isType && object.getClassName) {
  9887. className = object.getClassName();
  9888. }
  9889. else {
  9890. if (object instanceof Object) {
  9891. var classObj = isType ? object : Object.getPrototypeOf(object);
  9892. className = classObj.constructor["__bjsclassName__"];
  9893. moduleName = classObj.constructor["__bjsmoduleName__"];
  9894. }
  9895. if (!className) {
  9896. className = typeof object;
  9897. }
  9898. }
  9899. if (!className) {
  9900. return null;
  9901. }
  9902. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9903. };
  9904. /**
  9905. * 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.
  9906. * @param array
  9907. */
  9908. Tools.arrayOrStringFeeder = function (array) {
  9909. return function (index) {
  9910. if (index >= array.length) {
  9911. return null;
  9912. }
  9913. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9914. if (val && val.getHashCode) {
  9915. val = val.getHashCode();
  9916. }
  9917. if (typeof val === "string") {
  9918. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9919. }
  9920. return val;
  9921. };
  9922. };
  9923. /**
  9924. * Compute the hashCode of a stream of number
  9925. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9926. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9927. * @return the hash code computed
  9928. */
  9929. Tools.hashCodeFromStream = function (feeder) {
  9930. // Based from here: http://stackoverflow.com/a/7616484/802124
  9931. var hash = 0;
  9932. var index = 0;
  9933. var chr = feeder(index++);
  9934. while (chr != null) {
  9935. hash = ((hash << 5) - hash) + chr;
  9936. hash |= 0; // Convert to 32bit integer
  9937. chr = feeder(index++);
  9938. }
  9939. return hash;
  9940. };
  9941. /**
  9942. * Returns a promise that resolves after the given amount of time.
  9943. * @param delay Number of milliseconds to delay
  9944. * @returns Promise that resolves after the given amount of time
  9945. */
  9946. Tools.DelayAsync = function (delay) {
  9947. return new Promise(function (resolve) {
  9948. setTimeout(function () {
  9949. resolve();
  9950. }, delay);
  9951. });
  9952. };
  9953. /**
  9954. * Gets the current gradient from an array of IValueGradient
  9955. * @param ratio defines the current ratio to get
  9956. * @param gradients defines the array of IValueGradient
  9957. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9958. */
  9959. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9960. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9961. var currentGradient = gradients[gradientIndex];
  9962. var nextGradient = gradients[gradientIndex + 1];
  9963. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9964. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9965. updateFunc(currentGradient, nextGradient, scale);
  9966. }
  9967. }
  9968. };
  9969. Tools.BaseUrl = "";
  9970. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9971. /**
  9972. * Default behaviour for cors in the application.
  9973. * It can be a string if the expected behavior is identical in the entire app.
  9974. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9975. */
  9976. Tools.CorsBehavior = "anonymous";
  9977. Tools.UseFallbackTexture = true;
  9978. /**
  9979. * Use this object to register external classes like custom textures or material
  9980. * to allow the laoders to instantiate them
  9981. */
  9982. Tools.RegisteredExternalClasses = {};
  9983. // Used in case of a texture loading problem
  9984. 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";
  9985. Tools._tmpFloatArray = new Float32Array(1);
  9986. Tools.PreprocessUrl = function (url) {
  9987. return url;
  9988. };
  9989. // Logs
  9990. Tools._NoneLogLevel = 0;
  9991. Tools._MessageLogLevel = 1;
  9992. Tools._WarningLogLevel = 2;
  9993. Tools._ErrorLogLevel = 4;
  9994. Tools._LogCache = "";
  9995. Tools.errorsCount = 0;
  9996. Tools.Log = Tools._LogEnabled;
  9997. Tools.Warn = Tools._WarnEnabled;
  9998. Tools.Error = Tools._ErrorEnabled;
  9999. // Performances
  10000. Tools._PerformanceNoneLogLevel = 0;
  10001. Tools._PerformanceUserMarkLogLevel = 1;
  10002. Tools._PerformanceConsoleLogLevel = 2;
  10003. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10004. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10005. return Tools;
  10006. }());
  10007. BABYLON.Tools = Tools;
  10008. /**
  10009. * This class is used to track a performance counter which is number based.
  10010. * The user has access to many properties which give statistics of different nature
  10011. *
  10012. * The implementer can track two kinds of Performance Counter: time and count
  10013. * 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.
  10014. * 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.
  10015. */
  10016. var PerfCounter = /** @class */ (function () {
  10017. function PerfCounter() {
  10018. this._startMonitoringTime = 0;
  10019. this._min = 0;
  10020. this._max = 0;
  10021. this._average = 0;
  10022. this._lastSecAverage = 0;
  10023. this._current = 0;
  10024. this._totalValueCount = 0;
  10025. this._totalAccumulated = 0;
  10026. this._lastSecAccumulated = 0;
  10027. this._lastSecTime = 0;
  10028. this._lastSecValueCount = 0;
  10029. }
  10030. Object.defineProperty(PerfCounter.prototype, "min", {
  10031. /**
  10032. * Returns the smallest value ever
  10033. */
  10034. get: function () {
  10035. return this._min;
  10036. },
  10037. enumerable: true,
  10038. configurable: true
  10039. });
  10040. Object.defineProperty(PerfCounter.prototype, "max", {
  10041. /**
  10042. * Returns the biggest value ever
  10043. */
  10044. get: function () {
  10045. return this._max;
  10046. },
  10047. enumerable: true,
  10048. configurable: true
  10049. });
  10050. Object.defineProperty(PerfCounter.prototype, "average", {
  10051. /**
  10052. * Returns the average value since the performance counter is running
  10053. */
  10054. get: function () {
  10055. return this._average;
  10056. },
  10057. enumerable: true,
  10058. configurable: true
  10059. });
  10060. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10061. /**
  10062. * Returns the average value of the last second the counter was monitored
  10063. */
  10064. get: function () {
  10065. return this._lastSecAverage;
  10066. },
  10067. enumerable: true,
  10068. configurable: true
  10069. });
  10070. Object.defineProperty(PerfCounter.prototype, "current", {
  10071. /**
  10072. * Returns the current value
  10073. */
  10074. get: function () {
  10075. return this._current;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Object.defineProperty(PerfCounter.prototype, "total", {
  10081. get: function () {
  10082. return this._totalAccumulated;
  10083. },
  10084. enumerable: true,
  10085. configurable: true
  10086. });
  10087. Object.defineProperty(PerfCounter.prototype, "count", {
  10088. get: function () {
  10089. return this._totalValueCount;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. /**
  10095. * Call this method to start monitoring a new frame.
  10096. * 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.
  10097. */
  10098. PerfCounter.prototype.fetchNewFrame = function () {
  10099. this._totalValueCount++;
  10100. this._current = 0;
  10101. this._lastSecValueCount++;
  10102. };
  10103. /**
  10104. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10105. * @param newCount the count value to add to the monitored count
  10106. * @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.
  10107. */
  10108. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10109. if (!PerfCounter.Enabled) {
  10110. return;
  10111. }
  10112. this._current += newCount;
  10113. if (fetchResult) {
  10114. this._fetchResult();
  10115. }
  10116. };
  10117. /**
  10118. * Start monitoring this performance counter
  10119. */
  10120. PerfCounter.prototype.beginMonitoring = function () {
  10121. if (!PerfCounter.Enabled) {
  10122. return;
  10123. }
  10124. this._startMonitoringTime = Tools.Now;
  10125. };
  10126. /**
  10127. * Compute the time lapsed since the previous beginMonitoring() call.
  10128. * @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
  10129. */
  10130. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10131. if (newFrame === void 0) { newFrame = true; }
  10132. if (!PerfCounter.Enabled) {
  10133. return;
  10134. }
  10135. if (newFrame) {
  10136. this.fetchNewFrame();
  10137. }
  10138. var currentTime = Tools.Now;
  10139. this._current = currentTime - this._startMonitoringTime;
  10140. if (newFrame) {
  10141. this._fetchResult();
  10142. }
  10143. };
  10144. PerfCounter.prototype._fetchResult = function () {
  10145. this._totalAccumulated += this._current;
  10146. this._lastSecAccumulated += this._current;
  10147. // Min/Max update
  10148. this._min = Math.min(this._min, this._current);
  10149. this._max = Math.max(this._max, this._current);
  10150. this._average = this._totalAccumulated / this._totalValueCount;
  10151. // Reset last sec?
  10152. var now = Tools.Now;
  10153. if ((now - this._lastSecTime) > 1000) {
  10154. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10155. this._lastSecTime = now;
  10156. this._lastSecAccumulated = 0;
  10157. this._lastSecValueCount = 0;
  10158. }
  10159. };
  10160. PerfCounter.Enabled = true;
  10161. return PerfCounter;
  10162. }());
  10163. BABYLON.PerfCounter = PerfCounter;
  10164. /**
  10165. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10166. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10167. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10168. * @param name The name of the class, case should be preserved
  10169. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10170. */
  10171. function className(name, module) {
  10172. return function (target) {
  10173. target["__bjsclassName__"] = name;
  10174. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10175. };
  10176. }
  10177. BABYLON.className = className;
  10178. /**
  10179. * An implementation of a loop for asynchronous functions.
  10180. */
  10181. var AsyncLoop = /** @class */ (function () {
  10182. /**
  10183. * Constroctor.
  10184. * @param iterations the number of iterations.
  10185. * @param _fn the function to run each iteration
  10186. * @param _successCallback the callback that will be called upon succesful execution
  10187. * @param offset starting offset.
  10188. */
  10189. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10190. if (offset === void 0) { offset = 0; }
  10191. this.iterations = iterations;
  10192. this._fn = _fn;
  10193. this._successCallback = _successCallback;
  10194. this.index = offset - 1;
  10195. this._done = false;
  10196. }
  10197. /**
  10198. * Execute the next iteration. Must be called after the last iteration was finished.
  10199. */
  10200. AsyncLoop.prototype.executeNext = function () {
  10201. if (!this._done) {
  10202. if (this.index + 1 < this.iterations) {
  10203. ++this.index;
  10204. this._fn(this);
  10205. }
  10206. else {
  10207. this.breakLoop();
  10208. }
  10209. }
  10210. };
  10211. /**
  10212. * Break the loop and run the success callback.
  10213. */
  10214. AsyncLoop.prototype.breakLoop = function () {
  10215. this._done = true;
  10216. this._successCallback();
  10217. };
  10218. /**
  10219. * Helper function
  10220. */
  10221. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10222. if (offset === void 0) { offset = 0; }
  10223. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10224. loop.executeNext();
  10225. return loop;
  10226. };
  10227. /**
  10228. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10229. * @param iterations total number of iterations
  10230. * @param syncedIterations number of synchronous iterations in each async iteration.
  10231. * @param fn the function to call each iteration.
  10232. * @param callback a success call back that will be called when iterating stops.
  10233. * @param breakFunction a break condition (optional)
  10234. * @param timeout timeout settings for the setTimeout function. default - 0.
  10235. * @constructor
  10236. */
  10237. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10238. if (timeout === void 0) { timeout = 0; }
  10239. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10240. if (breakFunction && breakFunction())
  10241. loop.breakLoop();
  10242. else {
  10243. setTimeout(function () {
  10244. for (var i = 0; i < syncedIterations; ++i) {
  10245. var iteration = (loop.index * syncedIterations) + i;
  10246. if (iteration >= iterations)
  10247. break;
  10248. fn(iteration);
  10249. if (breakFunction && breakFunction()) {
  10250. loop.breakLoop();
  10251. break;
  10252. }
  10253. }
  10254. loop.executeNext();
  10255. }, timeout);
  10256. }
  10257. }, callback);
  10258. };
  10259. return AsyncLoop;
  10260. }());
  10261. BABYLON.AsyncLoop = AsyncLoop;
  10262. })(BABYLON || (BABYLON = {}));
  10263. //# sourceMappingURL=babylon.tools.js.map
  10264. var BABYLON;
  10265. (function (BABYLON) {
  10266. var PromiseStates;
  10267. (function (PromiseStates) {
  10268. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10269. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10270. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10271. })(PromiseStates || (PromiseStates = {}));
  10272. var FulFillmentAgregator = /** @class */ (function () {
  10273. function FulFillmentAgregator() {
  10274. this.count = 0;
  10275. this.target = 0;
  10276. this.results = [];
  10277. }
  10278. return FulFillmentAgregator;
  10279. }());
  10280. var InternalPromise = /** @class */ (function () {
  10281. function InternalPromise(resolver) {
  10282. var _this = this;
  10283. this._state = PromiseStates.Pending;
  10284. this._children = new Array();
  10285. this._rejectWasConsumed = false;
  10286. if (!resolver) {
  10287. return;
  10288. }
  10289. try {
  10290. resolver(function (value) {
  10291. _this._resolve(value);
  10292. }, function (reason) {
  10293. _this._reject(reason);
  10294. });
  10295. }
  10296. catch (e) {
  10297. this._reject(e);
  10298. }
  10299. }
  10300. Object.defineProperty(InternalPromise.prototype, "_result", {
  10301. get: function () {
  10302. return this._resultValue;
  10303. },
  10304. set: function (value) {
  10305. this._resultValue = value;
  10306. if (this._parent && this._parent._result === undefined) {
  10307. this._parent._result = value;
  10308. }
  10309. },
  10310. enumerable: true,
  10311. configurable: true
  10312. });
  10313. InternalPromise.prototype.catch = function (onRejected) {
  10314. return this.then(undefined, onRejected);
  10315. };
  10316. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10317. var _this = this;
  10318. var newPromise = new InternalPromise();
  10319. newPromise._onFulfilled = onFulfilled;
  10320. newPromise._onRejected = onRejected;
  10321. // Composition
  10322. this._children.push(newPromise);
  10323. newPromise._parent = this;
  10324. if (this._state !== PromiseStates.Pending) {
  10325. BABYLON.Tools.SetImmediate(function () {
  10326. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10327. var returnedValue = newPromise._resolve(_this._result);
  10328. if (returnedValue !== undefined && returnedValue !== null) {
  10329. if (returnedValue._state !== undefined) {
  10330. var returnedPromise = returnedValue;
  10331. newPromise._children.push(returnedPromise);
  10332. returnedPromise._parent = newPromise;
  10333. newPromise = returnedPromise;
  10334. }
  10335. else {
  10336. newPromise._result = returnedValue;
  10337. }
  10338. }
  10339. }
  10340. else {
  10341. newPromise._reject(_this._reason);
  10342. }
  10343. });
  10344. }
  10345. return newPromise;
  10346. };
  10347. InternalPromise.prototype._moveChildren = function (children) {
  10348. var _this = this;
  10349. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10350. this._children.forEach(function (child) {
  10351. child._parent = _this;
  10352. });
  10353. if (this._state === PromiseStates.Fulfilled) {
  10354. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10355. var child = _b[_i];
  10356. child._resolve(this._result);
  10357. }
  10358. }
  10359. else if (this._state === PromiseStates.Rejected) {
  10360. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10361. var child = _d[_c];
  10362. child._reject(this._reason);
  10363. }
  10364. }
  10365. var _a;
  10366. };
  10367. InternalPromise.prototype._resolve = function (value) {
  10368. try {
  10369. this._state = PromiseStates.Fulfilled;
  10370. var returnedValue = null;
  10371. if (this._onFulfilled) {
  10372. returnedValue = this._onFulfilled(value);
  10373. }
  10374. if (returnedValue !== undefined && returnedValue !== null) {
  10375. if (returnedValue._state !== undefined) {
  10376. // Transmit children
  10377. var returnedPromise = returnedValue;
  10378. returnedPromise._parent = this;
  10379. returnedPromise._moveChildren(this._children);
  10380. value = returnedPromise._result;
  10381. }
  10382. else {
  10383. value = returnedValue;
  10384. }
  10385. }
  10386. this._result = value;
  10387. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10388. var child = _a[_i];
  10389. child._resolve(value);
  10390. }
  10391. this._children.length = 0;
  10392. delete this._onFulfilled;
  10393. delete this._onRejected;
  10394. }
  10395. catch (e) {
  10396. this._reject(e, true);
  10397. }
  10398. };
  10399. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10400. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10401. this._state = PromiseStates.Rejected;
  10402. this._reason = reason;
  10403. if (this._onRejected && !onLocalThrow) {
  10404. try {
  10405. this._onRejected(reason);
  10406. this._rejectWasConsumed = true;
  10407. }
  10408. catch (e) {
  10409. reason = e;
  10410. }
  10411. }
  10412. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10413. var child = _a[_i];
  10414. if (this._rejectWasConsumed) {
  10415. child._resolve(null);
  10416. }
  10417. else {
  10418. child._reject(reason);
  10419. }
  10420. }
  10421. this._children.length = 0;
  10422. delete this._onFulfilled;
  10423. delete this._onRejected;
  10424. };
  10425. InternalPromise.resolve = function (value) {
  10426. var newPromise = new InternalPromise();
  10427. newPromise._resolve(value);
  10428. return newPromise;
  10429. };
  10430. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10431. promise.then(function (value) {
  10432. agregator.results[index] = value;
  10433. agregator.count++;
  10434. if (agregator.count === agregator.target) {
  10435. agregator.rootPromise._resolve(agregator.results);
  10436. }
  10437. return null;
  10438. }, function (reason) {
  10439. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10440. agregator.rootPromise._reject(reason);
  10441. }
  10442. });
  10443. };
  10444. InternalPromise.all = function (promises) {
  10445. var newPromise = new InternalPromise();
  10446. var agregator = new FulFillmentAgregator();
  10447. agregator.target = promises.length;
  10448. agregator.rootPromise = newPromise;
  10449. if (promises.length) {
  10450. for (var index = 0; index < promises.length; index++) {
  10451. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10452. }
  10453. }
  10454. else {
  10455. newPromise._resolve([]);
  10456. }
  10457. return newPromise;
  10458. };
  10459. InternalPromise.race = function (promises) {
  10460. var newPromise = new InternalPromise();
  10461. if (promises.length) {
  10462. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10463. var promise = promises_1[_i];
  10464. promise.then(function (value) {
  10465. if (newPromise) {
  10466. newPromise._resolve(value);
  10467. newPromise = null;
  10468. }
  10469. return null;
  10470. }, function (reason) {
  10471. if (newPromise) {
  10472. newPromise._reject(reason);
  10473. newPromise = null;
  10474. }
  10475. });
  10476. }
  10477. }
  10478. return newPromise;
  10479. };
  10480. return InternalPromise;
  10481. }());
  10482. /**
  10483. * Helper class that provides a small promise polyfill
  10484. */
  10485. var PromisePolyfill = /** @class */ (function () {
  10486. function PromisePolyfill() {
  10487. }
  10488. /**
  10489. * Static function used to check if the polyfill is required
  10490. * If this is the case then the function will inject the polyfill to window.Promise
  10491. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10492. */
  10493. PromisePolyfill.Apply = function (force) {
  10494. if (force === void 0) { force = false; }
  10495. if (force || typeof Promise === 'undefined') {
  10496. var root = window;
  10497. root.Promise = InternalPromise;
  10498. }
  10499. };
  10500. return PromisePolyfill;
  10501. }());
  10502. BABYLON.PromisePolyfill = PromisePolyfill;
  10503. })(BABYLON || (BABYLON = {}));
  10504. //# sourceMappingURL=babylon.promise.js.map
  10505. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10506. var BABYLON;
  10507. (function (BABYLON) {
  10508. /**
  10509. * Helper class to push actions to a pool of workers.
  10510. */
  10511. var WorkerPool = /** @class */ (function () {
  10512. /**
  10513. * Constructor
  10514. * @param workers Array of workers to use for actions
  10515. */
  10516. function WorkerPool(workers) {
  10517. this._pendingActions = new Array();
  10518. this._workerInfos = workers.map(function (worker) { return ({
  10519. worker: worker,
  10520. active: false
  10521. }); });
  10522. }
  10523. /**
  10524. * Terminates all workers and clears any pending actions.
  10525. */
  10526. WorkerPool.prototype.dispose = function () {
  10527. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10528. var workerInfo = _a[_i];
  10529. workerInfo.worker.terminate();
  10530. }
  10531. delete this._workerInfos;
  10532. delete this._pendingActions;
  10533. };
  10534. /**
  10535. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10536. * pended until a worker has completed its action.
  10537. * @param action The action to perform. Call onComplete when the action is complete.
  10538. */
  10539. WorkerPool.prototype.push = function (action) {
  10540. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10541. var workerInfo = _a[_i];
  10542. if (!workerInfo.active) {
  10543. this._execute(workerInfo, action);
  10544. return;
  10545. }
  10546. }
  10547. this._pendingActions.push(action);
  10548. };
  10549. WorkerPool.prototype._execute = function (workerInfo, action) {
  10550. var _this = this;
  10551. workerInfo.active = true;
  10552. action(workerInfo.worker, function () {
  10553. workerInfo.active = false;
  10554. var nextAction = _this._pendingActions.shift();
  10555. if (nextAction) {
  10556. _this._execute(workerInfo, nextAction);
  10557. }
  10558. });
  10559. };
  10560. return WorkerPool;
  10561. }());
  10562. BABYLON.WorkerPool = WorkerPool;
  10563. })(BABYLON || (BABYLON = {}));
  10564. //# sourceMappingURL=babylon.workerPool.js.map
  10565. var BABYLON;
  10566. (function (BABYLON) {
  10567. /**
  10568. * @hidden
  10569. **/
  10570. var _AlphaState = /** @class */ (function () {
  10571. /**
  10572. * Initializes the state.
  10573. */
  10574. function _AlphaState() {
  10575. this._isAlphaBlendDirty = false;
  10576. this._isBlendFunctionParametersDirty = false;
  10577. this._isBlendEquationParametersDirty = false;
  10578. this._isBlendConstantsDirty = false;
  10579. this._alphaBlend = false;
  10580. this._blendFunctionParameters = new Array(4);
  10581. this._blendEquationParameters = new Array(2);
  10582. this._blendConstants = new Array(4);
  10583. this.reset();
  10584. }
  10585. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10586. get: function () {
  10587. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10588. },
  10589. enumerable: true,
  10590. configurable: true
  10591. });
  10592. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10593. get: function () {
  10594. return this._alphaBlend;
  10595. },
  10596. set: function (value) {
  10597. if (this._alphaBlend === value) {
  10598. return;
  10599. }
  10600. this._alphaBlend = value;
  10601. this._isAlphaBlendDirty = true;
  10602. },
  10603. enumerable: true,
  10604. configurable: true
  10605. });
  10606. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10607. if (this._blendConstants[0] === r &&
  10608. this._blendConstants[1] === g &&
  10609. this._blendConstants[2] === b &&
  10610. this._blendConstants[3] === a) {
  10611. return;
  10612. }
  10613. this._blendConstants[0] = r;
  10614. this._blendConstants[1] = g;
  10615. this._blendConstants[2] = b;
  10616. this._blendConstants[3] = a;
  10617. this._isBlendConstantsDirty = true;
  10618. };
  10619. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10620. if (this._blendFunctionParameters[0] === value0 &&
  10621. this._blendFunctionParameters[1] === value1 &&
  10622. this._blendFunctionParameters[2] === value2 &&
  10623. this._blendFunctionParameters[3] === value3) {
  10624. return;
  10625. }
  10626. this._blendFunctionParameters[0] = value0;
  10627. this._blendFunctionParameters[1] = value1;
  10628. this._blendFunctionParameters[2] = value2;
  10629. this._blendFunctionParameters[3] = value3;
  10630. this._isBlendFunctionParametersDirty = true;
  10631. };
  10632. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10633. if (this._blendEquationParameters[0] === rgb &&
  10634. this._blendEquationParameters[1] === alpha) {
  10635. return;
  10636. }
  10637. this._blendEquationParameters[0] = rgb;
  10638. this._blendEquationParameters[1] = alpha;
  10639. this._isBlendEquationParametersDirty = true;
  10640. };
  10641. _AlphaState.prototype.reset = function () {
  10642. this._alphaBlend = false;
  10643. this._blendFunctionParameters[0] = null;
  10644. this._blendFunctionParameters[1] = null;
  10645. this._blendFunctionParameters[2] = null;
  10646. this._blendFunctionParameters[3] = null;
  10647. this._blendEquationParameters[0] = null;
  10648. this._blendEquationParameters[1] = null;
  10649. this._blendConstants[0] = null;
  10650. this._blendConstants[1] = null;
  10651. this._blendConstants[2] = null;
  10652. this._blendConstants[3] = null;
  10653. this._isAlphaBlendDirty = true;
  10654. this._isBlendFunctionParametersDirty = false;
  10655. this._isBlendEquationParametersDirty = false;
  10656. this._isBlendConstantsDirty = false;
  10657. };
  10658. _AlphaState.prototype.apply = function (gl) {
  10659. if (!this.isDirty) {
  10660. return;
  10661. }
  10662. // Alpha blend
  10663. if (this._isAlphaBlendDirty) {
  10664. if (this._alphaBlend) {
  10665. gl.enable(gl.BLEND);
  10666. }
  10667. else {
  10668. gl.disable(gl.BLEND);
  10669. }
  10670. this._isAlphaBlendDirty = false;
  10671. }
  10672. // Alpha function
  10673. if (this._isBlendFunctionParametersDirty) {
  10674. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10675. this._isBlendFunctionParametersDirty = false;
  10676. }
  10677. // Alpha equation
  10678. if (this._isBlendEquationParametersDirty) {
  10679. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10680. this._isBlendEquationParametersDirty = false;
  10681. }
  10682. // Constants
  10683. if (this._isBlendConstantsDirty) {
  10684. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10685. this._isBlendConstantsDirty = false;
  10686. }
  10687. };
  10688. return _AlphaState;
  10689. }());
  10690. BABYLON._AlphaState = _AlphaState;
  10691. })(BABYLON || (BABYLON = {}));
  10692. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10693. var BABYLON;
  10694. (function (BABYLON) {
  10695. /**
  10696. * @hidden
  10697. **/
  10698. var _DepthCullingState = /** @class */ (function () {
  10699. /**
  10700. * Initializes the state.
  10701. */
  10702. function _DepthCullingState() {
  10703. this._isDepthTestDirty = false;
  10704. this._isDepthMaskDirty = false;
  10705. this._isDepthFuncDirty = false;
  10706. this._isCullFaceDirty = false;
  10707. this._isCullDirty = false;
  10708. this._isZOffsetDirty = false;
  10709. this._isFrontFaceDirty = false;
  10710. this.reset();
  10711. }
  10712. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10713. get: function () {
  10714. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10720. get: function () {
  10721. return this._zOffset;
  10722. },
  10723. set: function (value) {
  10724. if (this._zOffset === value) {
  10725. return;
  10726. }
  10727. this._zOffset = value;
  10728. this._isZOffsetDirty = true;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10734. get: function () {
  10735. return this._cullFace;
  10736. },
  10737. set: function (value) {
  10738. if (this._cullFace === value) {
  10739. return;
  10740. }
  10741. this._cullFace = value;
  10742. this._isCullFaceDirty = true;
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10748. get: function () {
  10749. return this._cull;
  10750. },
  10751. set: function (value) {
  10752. if (this._cull === value) {
  10753. return;
  10754. }
  10755. this._cull = value;
  10756. this._isCullDirty = true;
  10757. },
  10758. enumerable: true,
  10759. configurable: true
  10760. });
  10761. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10762. get: function () {
  10763. return this._depthFunc;
  10764. },
  10765. set: function (value) {
  10766. if (this._depthFunc === value) {
  10767. return;
  10768. }
  10769. this._depthFunc = value;
  10770. this._isDepthFuncDirty = true;
  10771. },
  10772. enumerable: true,
  10773. configurable: true
  10774. });
  10775. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10776. get: function () {
  10777. return this._depthMask;
  10778. },
  10779. set: function (value) {
  10780. if (this._depthMask === value) {
  10781. return;
  10782. }
  10783. this._depthMask = value;
  10784. this._isDepthMaskDirty = true;
  10785. },
  10786. enumerable: true,
  10787. configurable: true
  10788. });
  10789. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10790. get: function () {
  10791. return this._depthTest;
  10792. },
  10793. set: function (value) {
  10794. if (this._depthTest === value) {
  10795. return;
  10796. }
  10797. this._depthTest = value;
  10798. this._isDepthTestDirty = true;
  10799. },
  10800. enumerable: true,
  10801. configurable: true
  10802. });
  10803. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10804. get: function () {
  10805. return this._frontFace;
  10806. },
  10807. set: function (value) {
  10808. if (this._frontFace === value) {
  10809. return;
  10810. }
  10811. this._frontFace = value;
  10812. this._isFrontFaceDirty = true;
  10813. },
  10814. enumerable: true,
  10815. configurable: true
  10816. });
  10817. _DepthCullingState.prototype.reset = function () {
  10818. this._depthMask = true;
  10819. this._depthTest = true;
  10820. this._depthFunc = null;
  10821. this._cullFace = null;
  10822. this._cull = null;
  10823. this._zOffset = 0;
  10824. this._frontFace = null;
  10825. this._isDepthTestDirty = true;
  10826. this._isDepthMaskDirty = true;
  10827. this._isDepthFuncDirty = false;
  10828. this._isCullFaceDirty = false;
  10829. this._isCullDirty = false;
  10830. this._isZOffsetDirty = false;
  10831. this._isFrontFaceDirty = false;
  10832. };
  10833. _DepthCullingState.prototype.apply = function (gl) {
  10834. if (!this.isDirty) {
  10835. return;
  10836. }
  10837. // Cull
  10838. if (this._isCullDirty) {
  10839. if (this.cull) {
  10840. gl.enable(gl.CULL_FACE);
  10841. }
  10842. else {
  10843. gl.disable(gl.CULL_FACE);
  10844. }
  10845. this._isCullDirty = false;
  10846. }
  10847. // Cull face
  10848. if (this._isCullFaceDirty) {
  10849. gl.cullFace(this.cullFace);
  10850. this._isCullFaceDirty = false;
  10851. }
  10852. // Depth mask
  10853. if (this._isDepthMaskDirty) {
  10854. gl.depthMask(this.depthMask);
  10855. this._isDepthMaskDirty = false;
  10856. }
  10857. // Depth test
  10858. if (this._isDepthTestDirty) {
  10859. if (this.depthTest) {
  10860. gl.enable(gl.DEPTH_TEST);
  10861. }
  10862. else {
  10863. gl.disable(gl.DEPTH_TEST);
  10864. }
  10865. this._isDepthTestDirty = false;
  10866. }
  10867. // Depth func
  10868. if (this._isDepthFuncDirty) {
  10869. gl.depthFunc(this.depthFunc);
  10870. this._isDepthFuncDirty = false;
  10871. }
  10872. // zOffset
  10873. if (this._isZOffsetDirty) {
  10874. if (this.zOffset) {
  10875. gl.enable(gl.POLYGON_OFFSET_FILL);
  10876. gl.polygonOffset(this.zOffset, 0);
  10877. }
  10878. else {
  10879. gl.disable(gl.POLYGON_OFFSET_FILL);
  10880. }
  10881. this._isZOffsetDirty = false;
  10882. }
  10883. // Front face
  10884. if (this._isFrontFaceDirty) {
  10885. gl.frontFace(this.frontFace);
  10886. this._isFrontFaceDirty = false;
  10887. }
  10888. };
  10889. return _DepthCullingState;
  10890. }());
  10891. BABYLON._DepthCullingState = _DepthCullingState;
  10892. })(BABYLON || (BABYLON = {}));
  10893. //# sourceMappingURL=babylon.depthCullingState.js.map
  10894. var BABYLON;
  10895. (function (BABYLON) {
  10896. /**
  10897. * @hidden
  10898. **/
  10899. var _StencilState = /** @class */ (function () {
  10900. function _StencilState() {
  10901. this._isStencilTestDirty = false;
  10902. this._isStencilMaskDirty = false;
  10903. this._isStencilFuncDirty = false;
  10904. this._isStencilOpDirty = false;
  10905. this.reset();
  10906. }
  10907. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10908. get: function () {
  10909. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10915. get: function () {
  10916. return this._stencilFunc;
  10917. },
  10918. set: function (value) {
  10919. if (this._stencilFunc === value) {
  10920. return;
  10921. }
  10922. this._stencilFunc = value;
  10923. this._isStencilFuncDirty = true;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10929. get: function () {
  10930. return this._stencilFuncRef;
  10931. },
  10932. set: function (value) {
  10933. if (this._stencilFuncRef === value) {
  10934. return;
  10935. }
  10936. this._stencilFuncRef = value;
  10937. this._isStencilFuncDirty = true;
  10938. },
  10939. enumerable: true,
  10940. configurable: true
  10941. });
  10942. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10943. get: function () {
  10944. return this._stencilFuncMask;
  10945. },
  10946. set: function (value) {
  10947. if (this._stencilFuncMask === value) {
  10948. return;
  10949. }
  10950. this._stencilFuncMask = value;
  10951. this._isStencilFuncDirty = true;
  10952. },
  10953. enumerable: true,
  10954. configurable: true
  10955. });
  10956. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10957. get: function () {
  10958. return this._stencilOpStencilFail;
  10959. },
  10960. set: function (value) {
  10961. if (this._stencilOpStencilFail === value) {
  10962. return;
  10963. }
  10964. this._stencilOpStencilFail = value;
  10965. this._isStencilOpDirty = true;
  10966. },
  10967. enumerable: true,
  10968. configurable: true
  10969. });
  10970. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10971. get: function () {
  10972. return this._stencilOpDepthFail;
  10973. },
  10974. set: function (value) {
  10975. if (this._stencilOpDepthFail === value) {
  10976. return;
  10977. }
  10978. this._stencilOpDepthFail = value;
  10979. this._isStencilOpDirty = true;
  10980. },
  10981. enumerable: true,
  10982. configurable: true
  10983. });
  10984. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10985. get: function () {
  10986. return this._stencilOpStencilDepthPass;
  10987. },
  10988. set: function (value) {
  10989. if (this._stencilOpStencilDepthPass === value) {
  10990. return;
  10991. }
  10992. this._stencilOpStencilDepthPass = value;
  10993. this._isStencilOpDirty = true;
  10994. },
  10995. enumerable: true,
  10996. configurable: true
  10997. });
  10998. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10999. get: function () {
  11000. return this._stencilMask;
  11001. },
  11002. set: function (value) {
  11003. if (this._stencilMask === value) {
  11004. return;
  11005. }
  11006. this._stencilMask = value;
  11007. this._isStencilMaskDirty = true;
  11008. },
  11009. enumerable: true,
  11010. configurable: true
  11011. });
  11012. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11013. get: function () {
  11014. return this._stencilTest;
  11015. },
  11016. set: function (value) {
  11017. if (this._stencilTest === value) {
  11018. return;
  11019. }
  11020. this._stencilTest = value;
  11021. this._isStencilTestDirty = true;
  11022. },
  11023. enumerable: true,
  11024. configurable: true
  11025. });
  11026. _StencilState.prototype.reset = function () {
  11027. this._stencilTest = false;
  11028. this._stencilMask = 0xFF;
  11029. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11030. this._stencilFuncRef = 1;
  11031. this._stencilFuncMask = 0xFF;
  11032. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11033. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11034. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11035. this._isStencilTestDirty = true;
  11036. this._isStencilMaskDirty = true;
  11037. this._isStencilFuncDirty = true;
  11038. this._isStencilOpDirty = true;
  11039. };
  11040. _StencilState.prototype.apply = function (gl) {
  11041. if (!this.isDirty) {
  11042. return;
  11043. }
  11044. // Stencil test
  11045. if (this._isStencilTestDirty) {
  11046. if (this.stencilTest) {
  11047. gl.enable(gl.STENCIL_TEST);
  11048. }
  11049. else {
  11050. gl.disable(gl.STENCIL_TEST);
  11051. }
  11052. this._isStencilTestDirty = false;
  11053. }
  11054. // Stencil mask
  11055. if (this._isStencilMaskDirty) {
  11056. gl.stencilMask(this.stencilMask);
  11057. this._isStencilMaskDirty = false;
  11058. }
  11059. // Stencil func
  11060. if (this._isStencilFuncDirty) {
  11061. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11062. this._isStencilFuncDirty = false;
  11063. }
  11064. // Stencil op
  11065. if (this._isStencilOpDirty) {
  11066. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11067. this._isStencilOpDirty = false;
  11068. }
  11069. };
  11070. return _StencilState;
  11071. }());
  11072. BABYLON._StencilState = _StencilState;
  11073. })(BABYLON || (BABYLON = {}));
  11074. //# sourceMappingURL=babylon.stencilState.js.map
  11075. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11076. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11077. s = arguments[i];
  11078. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11079. t[p] = s[p];
  11080. }
  11081. return t;
  11082. };
  11083. var BABYLON;
  11084. (function (BABYLON) {
  11085. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11086. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11087. };
  11088. var compileRawShader = function (gl, source, type) {
  11089. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11090. gl.shaderSource(shader, source);
  11091. gl.compileShader(shader);
  11092. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11093. var log = gl.getShaderInfoLog(shader);
  11094. if (log) {
  11095. throw new Error(log);
  11096. }
  11097. }
  11098. if (!shader) {
  11099. throw new Error("Something went wrong while compile the shader.");
  11100. }
  11101. return shader;
  11102. };
  11103. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11104. var magFilter = gl.NEAREST;
  11105. var minFilter = gl.NEAREST;
  11106. switch (samplingMode) {
  11107. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11108. magFilter = gl.LINEAR;
  11109. if (generateMipMaps) {
  11110. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11111. }
  11112. else {
  11113. minFilter = gl.LINEAR;
  11114. }
  11115. break;
  11116. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11117. magFilter = gl.LINEAR;
  11118. if (generateMipMaps) {
  11119. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11120. }
  11121. else {
  11122. minFilter = gl.LINEAR;
  11123. }
  11124. break;
  11125. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11126. magFilter = gl.NEAREST;
  11127. if (generateMipMaps) {
  11128. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11129. }
  11130. else {
  11131. minFilter = gl.NEAREST;
  11132. }
  11133. break;
  11134. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11135. magFilter = gl.NEAREST;
  11136. if (generateMipMaps) {
  11137. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11138. }
  11139. else {
  11140. minFilter = gl.NEAREST;
  11141. }
  11142. break;
  11143. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11144. magFilter = gl.NEAREST;
  11145. if (generateMipMaps) {
  11146. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11147. }
  11148. else {
  11149. minFilter = gl.LINEAR;
  11150. }
  11151. break;
  11152. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11153. magFilter = gl.NEAREST;
  11154. if (generateMipMaps) {
  11155. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11156. }
  11157. else {
  11158. minFilter = gl.LINEAR;
  11159. }
  11160. break;
  11161. case BABYLON.Texture.NEAREST_LINEAR:
  11162. magFilter = gl.NEAREST;
  11163. minFilter = gl.LINEAR;
  11164. break;
  11165. case BABYLON.Texture.NEAREST_NEAREST:
  11166. magFilter = gl.NEAREST;
  11167. minFilter = gl.NEAREST;
  11168. break;
  11169. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11170. magFilter = gl.LINEAR;
  11171. if (generateMipMaps) {
  11172. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11173. }
  11174. else {
  11175. minFilter = gl.NEAREST;
  11176. }
  11177. break;
  11178. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11179. magFilter = gl.LINEAR;
  11180. if (generateMipMaps) {
  11181. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11182. }
  11183. else {
  11184. minFilter = gl.NEAREST;
  11185. }
  11186. break;
  11187. case BABYLON.Texture.LINEAR_LINEAR:
  11188. magFilter = gl.LINEAR;
  11189. minFilter = gl.LINEAR;
  11190. break;
  11191. case BABYLON.Texture.LINEAR_NEAREST:
  11192. magFilter = gl.LINEAR;
  11193. minFilter = gl.NEAREST;
  11194. break;
  11195. }
  11196. return {
  11197. min: minFilter,
  11198. mag: magFilter
  11199. };
  11200. };
  11201. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11202. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11203. var img;
  11204. var onload = function () {
  11205. loadedImages[index] = img;
  11206. loadedImages._internalCount++;
  11207. if (scene) {
  11208. scene._removePendingData(img);
  11209. }
  11210. if (loadedImages._internalCount === 6) {
  11211. onfinish(loadedImages);
  11212. }
  11213. };
  11214. var onerror = function (message, exception) {
  11215. if (scene) {
  11216. scene._removePendingData(img);
  11217. }
  11218. if (onErrorCallBack) {
  11219. onErrorCallBack(message, exception);
  11220. }
  11221. };
  11222. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11223. if (scene) {
  11224. scene._addPendingData(img);
  11225. }
  11226. };
  11227. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11228. if (onError === void 0) { onError = null; }
  11229. var loadedImages = [];
  11230. loadedImages._internalCount = 0;
  11231. for (var index = 0; index < 6; index++) {
  11232. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11233. }
  11234. };
  11235. var BufferPointer = /** @class */ (function () {
  11236. function BufferPointer() {
  11237. }
  11238. return BufferPointer;
  11239. }());
  11240. /**
  11241. * Interface for attribute information associated with buffer instanciation
  11242. */
  11243. var InstancingAttributeInfo = /** @class */ (function () {
  11244. function InstancingAttributeInfo() {
  11245. }
  11246. return InstancingAttributeInfo;
  11247. }());
  11248. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11249. /**
  11250. * Define options used to create a render target texture
  11251. */
  11252. var RenderTargetCreationOptions = /** @class */ (function () {
  11253. function RenderTargetCreationOptions() {
  11254. }
  11255. return RenderTargetCreationOptions;
  11256. }());
  11257. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11258. /**
  11259. * Define options used to create a depth texture
  11260. */
  11261. var DepthTextureCreationOptions = /** @class */ (function () {
  11262. function DepthTextureCreationOptions() {
  11263. }
  11264. return DepthTextureCreationOptions;
  11265. }());
  11266. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11267. /**
  11268. * Class used to describe the capabilities of the engine relatively to the current browser
  11269. */
  11270. var EngineCapabilities = /** @class */ (function () {
  11271. function EngineCapabilities() {
  11272. }
  11273. return EngineCapabilities;
  11274. }());
  11275. BABYLON.EngineCapabilities = EngineCapabilities;
  11276. /**
  11277. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11278. */
  11279. var Engine = /** @class */ (function () {
  11280. /**
  11281. * Creates a new engine
  11282. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11283. * @param antialias defines enable antialiasing (default: false)
  11284. * @param options defines further options to be sent to the getContext() function
  11285. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11286. */
  11287. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11288. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11289. var _this = this;
  11290. // Public members
  11291. /**
  11292. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11293. */
  11294. this.forcePOTTextures = false;
  11295. /**
  11296. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11297. */
  11298. this.isFullscreen = false;
  11299. /**
  11300. * Gets a boolean indicating if the pointer is currently locked
  11301. */
  11302. this.isPointerLock = false;
  11303. /**
  11304. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11305. */
  11306. this.cullBackFaces = true;
  11307. /**
  11308. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11309. */
  11310. this.renderEvenInBackground = true;
  11311. /**
  11312. * Gets or sets a boolean indicating that cache can be kept between frames
  11313. */
  11314. this.preventCacheWipeBetweenFrames = false;
  11315. /**
  11316. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11317. **/
  11318. this.enableOfflineSupport = false;
  11319. /**
  11320. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11321. **/
  11322. this.disableManifestCheck = false;
  11323. /**
  11324. * Gets the list of created scenes
  11325. */
  11326. this.scenes = new Array();
  11327. /**
  11328. * Gets the list of created postprocesses
  11329. */
  11330. this.postProcesses = new Array();
  11331. // Observables
  11332. /**
  11333. * Observable event triggered each time the rendering canvas is resized
  11334. */
  11335. this.onResizeObservable = new BABYLON.Observable();
  11336. /**
  11337. * Observable event triggered each time the canvas loses focus
  11338. */
  11339. this.onCanvasBlurObservable = new BABYLON.Observable();
  11340. /**
  11341. * Observable event triggered each time the canvas gains focus
  11342. */
  11343. this.onCanvasFocusObservable = new BABYLON.Observable();
  11344. /**
  11345. * Observable event triggered each time the canvas receives pointerout event
  11346. */
  11347. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11348. /**
  11349. * Observable event triggered before each texture is initialized
  11350. */
  11351. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11352. //WebVR
  11353. this._vrDisplay = undefined;
  11354. this._vrSupported = false;
  11355. this._vrExclusivePointerMode = false;
  11356. // Uniform buffers list
  11357. /**
  11358. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11359. */
  11360. this.disableUniformBuffers = false;
  11361. /** @hidden */
  11362. this._uniformBuffers = new Array();
  11363. // Observables
  11364. /**
  11365. * Observable raised when the engine begins a new frame
  11366. */
  11367. this.onBeginFrameObservable = new BABYLON.Observable();
  11368. /**
  11369. * Observable raised when the engine ends the current frame
  11370. */
  11371. this.onEndFrameObservable = new BABYLON.Observable();
  11372. /**
  11373. * Observable raised when the engine is about to compile a shader
  11374. */
  11375. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11376. /**
  11377. * Observable raised when the engine has jsut compiled a shader
  11378. */
  11379. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11380. this._windowIsBackground = false;
  11381. this._webGLVersion = 1.0;
  11382. /** @hidden */
  11383. this._badOS = false;
  11384. /** @hidden */
  11385. this._badDesktopOS = false;
  11386. /**
  11387. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11388. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11389. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11390. */
  11391. this.disableTextureBindingOptimization = false;
  11392. /**
  11393. * Observable signaled when VR display mode changes
  11394. */
  11395. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11396. /**
  11397. * Observable signaled when VR request present is complete
  11398. */
  11399. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11400. /**
  11401. * Observable signaled when VR request present starts
  11402. */
  11403. this.onVRRequestPresentStart = new BABYLON.Observable();
  11404. this._colorWrite = true;
  11405. /** @hidden */
  11406. this._drawCalls = new BABYLON.PerfCounter();
  11407. /** @hidden */
  11408. this._textureCollisions = new BABYLON.PerfCounter();
  11409. this._renderingQueueLaunched = false;
  11410. this._activeRenderLoops = new Array();
  11411. // Deterministic lockstepMaxSteps
  11412. this._deterministicLockstep = false;
  11413. this._lockstepMaxSteps = 4;
  11414. // Lost context
  11415. /**
  11416. * Observable signaled when a context lost event is raised
  11417. */
  11418. this.onContextLostObservable = new BABYLON.Observable();
  11419. /**
  11420. * Observable signaled when a context restored event is raised
  11421. */
  11422. this.onContextRestoredObservable = new BABYLON.Observable();
  11423. this._contextWasLost = false;
  11424. this._doNotHandleContextLost = false;
  11425. // FPS
  11426. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11427. this._fps = 60;
  11428. this._deltaTime = 0;
  11429. /**
  11430. * Turn this value on if you want to pause FPS computation when in background
  11431. */
  11432. this.disablePerformanceMonitorInBackground = false;
  11433. // States
  11434. /** @hidden */
  11435. this._depthCullingState = new BABYLON._DepthCullingState();
  11436. /** @hidden */
  11437. this._stencilState = new BABYLON._StencilState();
  11438. /** @hidden */
  11439. this._alphaState = new BABYLON._AlphaState();
  11440. /** @hidden */
  11441. this._alphaMode = Engine.ALPHA_DISABLE;
  11442. // Cache
  11443. this._internalTexturesCache = new Array();
  11444. /** @hidden */
  11445. this._activeChannel = 0;
  11446. this._currentTextureChannel = -1;
  11447. /** @hidden */
  11448. this._boundTexturesCache = {};
  11449. this._compiledEffects = {};
  11450. this._vertexAttribArraysEnabled = [];
  11451. this._uintIndicesCurrentlySet = false;
  11452. this._currentBoundBuffer = new Array();
  11453. /** @hidden */
  11454. this._currentFramebuffer = null;
  11455. this._currentBufferPointers = new Array();
  11456. this._currentInstanceLocations = new Array();
  11457. this._currentInstanceBuffers = new Array();
  11458. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11459. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11460. this._vaoRecordInProgress = false;
  11461. this._mustWipeVertexAttributes = false;
  11462. this._nextFreeTextureSlots = new Array();
  11463. this._maxSimultaneousTextures = 0;
  11464. this._activeRequests = new Array();
  11465. // Hardware supported Compressed Textures
  11466. this._texturesSupported = new Array();
  11467. /**
  11468. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11469. */
  11470. this.premultipliedAlpha = true;
  11471. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11472. this._onVRFullScreenTriggered = function () {
  11473. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11474. //get the old size before we change
  11475. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11476. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11477. //get the width and height, change the render size
  11478. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11479. _this.setHardwareScalingLevel(1);
  11480. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11481. }
  11482. else {
  11483. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11484. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11485. }
  11486. };
  11487. this._unpackFlipYCached = null;
  11488. this._boundUniforms = {};
  11489. // Register promises
  11490. BABYLON.PromisePolyfill.Apply();
  11491. var canvas = null;
  11492. Engine.Instances.push(this);
  11493. if (!canvasOrContext) {
  11494. return;
  11495. }
  11496. options = options || {};
  11497. if (canvasOrContext.getContext) {
  11498. canvas = canvasOrContext;
  11499. this._renderingCanvas = canvas;
  11500. if (antialias != null) {
  11501. options.antialias = antialias;
  11502. }
  11503. if (options.deterministicLockstep === undefined) {
  11504. options.deterministicLockstep = false;
  11505. }
  11506. if (options.lockstepMaxSteps === undefined) {
  11507. options.lockstepMaxSteps = 4;
  11508. }
  11509. if (options.preserveDrawingBuffer === undefined) {
  11510. options.preserveDrawingBuffer = false;
  11511. }
  11512. if (options.audioEngine === undefined) {
  11513. options.audioEngine = true;
  11514. }
  11515. if (options.stencil === undefined) {
  11516. options.stencil = true;
  11517. }
  11518. if (options.premultipliedAlpha === false) {
  11519. this.premultipliedAlpha = false;
  11520. }
  11521. this._deterministicLockstep = options.deterministicLockstep;
  11522. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11523. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11524. // Exceptions
  11525. if (navigator && navigator.userAgent) {
  11526. var ua = navigator.userAgent;
  11527. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11528. var exception = _a[_i];
  11529. var key = exception.key;
  11530. var targets = exception.targets;
  11531. if (ua.indexOf(key) > -1) {
  11532. if (exception.capture && exception.captureConstraint) {
  11533. var capture = exception.capture;
  11534. var constraint = exception.captureConstraint;
  11535. var regex = new RegExp(capture);
  11536. var matches = regex.exec(ua);
  11537. if (matches && matches.length > 0) {
  11538. var capturedValue = parseInt(matches[matches.length - 1]);
  11539. if (capturedValue >= constraint) {
  11540. continue;
  11541. }
  11542. }
  11543. }
  11544. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11545. var target = targets_1[_b];
  11546. switch (target) {
  11547. case "uniformBuffer":
  11548. this.disableUniformBuffers = true;
  11549. break;
  11550. case "textureBindingOptimization":
  11551. this.disableTextureBindingOptimization = true;
  11552. break;
  11553. }
  11554. }
  11555. }
  11556. }
  11557. }
  11558. // GL
  11559. if (!options.disableWebGL2Support) {
  11560. try {
  11561. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11562. if (this._gl) {
  11563. this._webGLVersion = 2.0;
  11564. }
  11565. }
  11566. catch (e) {
  11567. // Do nothing
  11568. }
  11569. }
  11570. if (!this._gl) {
  11571. if (!canvas) {
  11572. throw new Error("The provided canvas is null or undefined.");
  11573. }
  11574. try {
  11575. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11576. }
  11577. catch (e) {
  11578. throw new Error("WebGL not supported");
  11579. }
  11580. }
  11581. if (!this._gl) {
  11582. throw new Error("WebGL not supported");
  11583. }
  11584. this._onCanvasFocus = function () {
  11585. _this.onCanvasFocusObservable.notifyObservers(_this);
  11586. };
  11587. this._onCanvasBlur = function () {
  11588. _this.onCanvasBlurObservable.notifyObservers(_this);
  11589. };
  11590. canvas.addEventListener("focus", this._onCanvasFocus);
  11591. canvas.addEventListener("blur", this._onCanvasBlur);
  11592. this._onBlur = function () {
  11593. if (_this.disablePerformanceMonitorInBackground) {
  11594. _this._performanceMonitor.disable();
  11595. }
  11596. _this._windowIsBackground = true;
  11597. };
  11598. this._onFocus = function () {
  11599. if (_this.disablePerformanceMonitorInBackground) {
  11600. _this._performanceMonitor.enable();
  11601. }
  11602. _this._windowIsBackground = false;
  11603. };
  11604. this._onCanvasPointerOut = function (ev) {
  11605. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11606. };
  11607. window.addEventListener("blur", this._onBlur);
  11608. window.addEventListener("focus", this._onFocus);
  11609. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11610. // Context lost
  11611. if (!this._doNotHandleContextLost) {
  11612. this._onContextLost = function (evt) {
  11613. evt.preventDefault();
  11614. _this._contextWasLost = true;
  11615. BABYLON.Tools.Warn("WebGL context lost.");
  11616. _this.onContextLostObservable.notifyObservers(_this);
  11617. };
  11618. this._onContextRestored = function (evt) {
  11619. // Adding a timeout to avoid race condition at browser level
  11620. setTimeout(function () {
  11621. // Rebuild gl context
  11622. _this._initGLContext();
  11623. // Rebuild effects
  11624. _this._rebuildEffects();
  11625. // Rebuild textures
  11626. _this._rebuildInternalTextures();
  11627. // Rebuild buffers
  11628. _this._rebuildBuffers();
  11629. // Cache
  11630. _this.wipeCaches(true);
  11631. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11632. _this.onContextRestoredObservable.notifyObservers(_this);
  11633. _this._contextWasLost = false;
  11634. }, 0);
  11635. };
  11636. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11637. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11638. }
  11639. }
  11640. else {
  11641. this._gl = canvasOrContext;
  11642. this._renderingCanvas = this._gl.canvas;
  11643. if (this._gl.renderbufferStorageMultisample) {
  11644. this._webGLVersion = 2.0;
  11645. }
  11646. options.stencil = this._gl.getContextAttributes().stencil;
  11647. }
  11648. // Viewport
  11649. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11650. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11651. this.resize();
  11652. this._isStencilEnable = options.stencil ? true : false;
  11653. this._initGLContext();
  11654. if (canvas) {
  11655. // Fullscreen
  11656. this._onFullscreenChange = function () {
  11657. if (document.fullscreen !== undefined) {
  11658. _this.isFullscreen = document.fullscreen;
  11659. }
  11660. else if (document.mozFullScreen !== undefined) {
  11661. _this.isFullscreen = document.mozFullScreen;
  11662. }
  11663. else if (document.webkitIsFullScreen !== undefined) {
  11664. _this.isFullscreen = document.webkitIsFullScreen;
  11665. }
  11666. else if (document.msIsFullScreen !== undefined) {
  11667. _this.isFullscreen = document.msIsFullScreen;
  11668. }
  11669. // Pointer lock
  11670. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11671. canvas.requestPointerLock = canvas.requestPointerLock ||
  11672. canvas.msRequestPointerLock ||
  11673. canvas.mozRequestPointerLock ||
  11674. canvas.webkitRequestPointerLock;
  11675. if (canvas.requestPointerLock) {
  11676. canvas.requestPointerLock();
  11677. }
  11678. }
  11679. };
  11680. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11681. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11682. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11683. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11684. // Pointer lock
  11685. this._onPointerLockChange = function () {
  11686. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11687. document.webkitPointerLockElement === canvas ||
  11688. document.msPointerLockElement === canvas ||
  11689. document.pointerLockElement === canvas);
  11690. };
  11691. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11692. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11693. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11694. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11695. this._onVRDisplayPointerRestricted = function () {
  11696. if (canvas) {
  11697. canvas.requestPointerLock();
  11698. }
  11699. };
  11700. this._onVRDisplayPointerUnrestricted = function () {
  11701. document.exitPointerLock();
  11702. };
  11703. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11704. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11705. }
  11706. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11707. Engine.audioEngine = new BABYLON.AudioEngine();
  11708. }
  11709. // Prepare buffer pointers
  11710. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11711. this._currentBufferPointers[i] = new BufferPointer();
  11712. }
  11713. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11714. // Load WebVR Devices
  11715. if (options.autoEnableWebVR) {
  11716. this.initWebVR();
  11717. }
  11718. // Detect if we are running on a faulty buggy OS.
  11719. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11720. // Detect if we are running on a faulty buggy desktop OS.
  11721. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11722. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11723. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11724. }
  11725. Object.defineProperty(Engine, "LastCreatedEngine", {
  11726. /**
  11727. * Gets the latest created engine
  11728. */
  11729. get: function () {
  11730. if (Engine.Instances.length === 0) {
  11731. return null;
  11732. }
  11733. return Engine.Instances[Engine.Instances.length - 1];
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. Object.defineProperty(Engine, "LastCreatedScene", {
  11739. /**
  11740. * Gets the latest created scene
  11741. */
  11742. get: function () {
  11743. var lastCreatedEngine = Engine.LastCreatedEngine;
  11744. if (!lastCreatedEngine) {
  11745. return null;
  11746. }
  11747. if (lastCreatedEngine.scenes.length === 0) {
  11748. return null;
  11749. }
  11750. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. /**
  11756. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11757. * @param flag defines which part of the materials must be marked as dirty
  11758. * @param predicate defines a predicate used to filter which materials should be affected
  11759. */
  11760. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11761. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11762. var engine = Engine.Instances[engineIndex];
  11763. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11764. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11765. }
  11766. }
  11767. };
  11768. Object.defineProperty(Engine, "NEVER", {
  11769. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11770. get: function () {
  11771. return Engine._NEVER;
  11772. },
  11773. enumerable: true,
  11774. configurable: true
  11775. });
  11776. Object.defineProperty(Engine, "ALWAYS", {
  11777. /** 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 */
  11778. get: function () {
  11779. return Engine._ALWAYS;
  11780. },
  11781. enumerable: true,
  11782. configurable: true
  11783. });
  11784. Object.defineProperty(Engine, "LESS", {
  11785. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11786. get: function () {
  11787. return Engine._LESS;
  11788. },
  11789. enumerable: true,
  11790. configurable: true
  11791. });
  11792. Object.defineProperty(Engine, "EQUAL", {
  11793. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11794. get: function () {
  11795. return Engine._EQUAL;
  11796. },
  11797. enumerable: true,
  11798. configurable: true
  11799. });
  11800. Object.defineProperty(Engine, "LEQUAL", {
  11801. /** 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 */
  11802. get: function () {
  11803. return Engine._LEQUAL;
  11804. },
  11805. enumerable: true,
  11806. configurable: true
  11807. });
  11808. Object.defineProperty(Engine, "GREATER", {
  11809. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11810. get: function () {
  11811. return Engine._GREATER;
  11812. },
  11813. enumerable: true,
  11814. configurable: true
  11815. });
  11816. Object.defineProperty(Engine, "GEQUAL", {
  11817. /** 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 */
  11818. get: function () {
  11819. return Engine._GEQUAL;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine, "NOTEQUAL", {
  11825. /** 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 */
  11826. get: function () {
  11827. return Engine._NOTEQUAL;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine, "KEEP", {
  11833. /** Passed to stencilOperation to specify that stencil value must be kept */
  11834. get: function () {
  11835. return Engine._KEEP;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine, "REPLACE", {
  11841. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11842. get: function () {
  11843. return Engine._REPLACE;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "INCR", {
  11849. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11850. get: function () {
  11851. return Engine._INCR;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(Engine, "DECR", {
  11857. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11858. get: function () {
  11859. return Engine._DECR;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(Engine, "INVERT", {
  11865. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11866. get: function () {
  11867. return Engine._INVERT;
  11868. },
  11869. enumerable: true,
  11870. configurable: true
  11871. });
  11872. Object.defineProperty(Engine, "INCR_WRAP", {
  11873. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11874. get: function () {
  11875. return Engine._INCR_WRAP;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine, "DECR_WRAP", {
  11881. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11882. get: function () {
  11883. return Engine._DECR_WRAP;
  11884. },
  11885. enumerable: true,
  11886. configurable: true
  11887. });
  11888. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11889. // Alpha
  11890. /** Defines that alpha blending is disabled */
  11891. get: function () {
  11892. return Engine._ALPHA_DISABLE;
  11893. },
  11894. enumerable: true,
  11895. configurable: true
  11896. });
  11897. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11898. /** Defines that alpha blending to SRC + DEST */
  11899. get: function () {
  11900. return Engine._ALPHA_ONEONE;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(Engine, "ALPHA_ADD", {
  11906. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11907. get: function () {
  11908. return Engine._ALPHA_ADD;
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11914. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11915. get: function () {
  11916. return Engine._ALPHA_COMBINE;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11922. /** Defines that alpha blending to DEST - SRC * DEST */
  11923. get: function () {
  11924. return Engine._ALPHA_SUBTRACT;
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11930. /** Defines that alpha blending to SRC * DEST */
  11931. get: function () {
  11932. return Engine._ALPHA_MULTIPLY;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11938. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11939. get: function () {
  11940. return Engine._ALPHA_MAXIMIZED;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11946. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11947. get: function () {
  11948. return Engine._ALPHA_PREMULTIPLIED;
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11954. /**
  11955. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11956. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11957. */
  11958. get: function () {
  11959. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11960. },
  11961. enumerable: true,
  11962. configurable: true
  11963. });
  11964. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11965. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11966. get: function () {
  11967. return Engine._ALPHA_INTERPOLATE;
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11973. /**
  11974. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11975. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11976. */
  11977. get: function () {
  11978. return Engine._ALPHA_SCREENMODE;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11984. // Delays
  11985. /** Defines that the ressource is not delayed*/
  11986. get: function () {
  11987. return Engine._DELAYLOADSTATE_NONE;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11993. /** Defines that the ressource was successfully delay loaded */
  11994. get: function () {
  11995. return Engine._DELAYLOADSTATE_LOADED;
  11996. },
  11997. enumerable: true,
  11998. configurable: true
  11999. });
  12000. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  12001. /** Defines that the ressource is currently delay loading */
  12002. get: function () {
  12003. return Engine._DELAYLOADSTATE_LOADING;
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  12009. /** Defines that the ressource is delayed and has not started loading */
  12010. get: function () {
  12011. return Engine._DELAYLOADSTATE_NOTLOADED;
  12012. },
  12013. enumerable: true,
  12014. configurable: true
  12015. });
  12016. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12017. /** ALPHA */
  12018. get: function () {
  12019. return Engine._TEXTUREFORMAT_ALPHA;
  12020. },
  12021. enumerable: true,
  12022. configurable: true
  12023. });
  12024. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12025. /** LUMINANCE */
  12026. get: function () {
  12027. return Engine._TEXTUREFORMAT_LUMINANCE;
  12028. },
  12029. enumerable: true,
  12030. configurable: true
  12031. });
  12032. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12033. /**
  12034. * R
  12035. */
  12036. get: function () {
  12037. return Engine._TEXTUREFORMAT_R;
  12038. },
  12039. enumerable: true,
  12040. configurable: true
  12041. });
  12042. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12043. /**
  12044. * RG
  12045. */
  12046. get: function () {
  12047. return Engine._TEXTUREFORMAT_RG;
  12048. },
  12049. enumerable: true,
  12050. configurable: true
  12051. });
  12052. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12053. /** LUMINANCE_ALPHA */
  12054. get: function () {
  12055. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12061. /** RGB */
  12062. get: function () {
  12063. return Engine._TEXTUREFORMAT_RGB;
  12064. },
  12065. enumerable: true,
  12066. configurable: true
  12067. });
  12068. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12069. /** RGBA */
  12070. get: function () {
  12071. return Engine._TEXTUREFORMAT_RGBA;
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12077. /** UNSIGNED_INT */
  12078. get: function () {
  12079. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12080. },
  12081. enumerable: true,
  12082. configurable: true
  12083. });
  12084. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12085. /** FLOAT */
  12086. get: function () {
  12087. return Engine._TEXTURETYPE_FLOAT;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12093. /** HALF_FLOAT */
  12094. get: function () {
  12095. return Engine._TEXTURETYPE_HALF_FLOAT;
  12096. },
  12097. enumerable: true,
  12098. configurable: true
  12099. });
  12100. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12101. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12102. get: function () {
  12103. return Engine._SCALEMODE_FLOOR;
  12104. },
  12105. enumerable: true,
  12106. configurable: true
  12107. });
  12108. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12109. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12110. get: function () {
  12111. return Engine._SCALEMODE_NEAREST;
  12112. },
  12113. enumerable: true,
  12114. configurable: true
  12115. });
  12116. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12117. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12118. get: function () {
  12119. return Engine._SCALEMODE_CEILING;
  12120. },
  12121. enumerable: true,
  12122. configurable: true
  12123. });
  12124. Object.defineProperty(Engine, "Version", {
  12125. /**
  12126. * Returns the current version of the framework
  12127. */
  12128. get: function () {
  12129. return "3.3.0-alpha.9";
  12130. },
  12131. enumerable: true,
  12132. configurable: true
  12133. });
  12134. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12135. /**
  12136. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12137. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12138. */
  12139. get: function () {
  12140. return this._vrExclusivePointerMode;
  12141. },
  12142. enumerable: true,
  12143. configurable: true
  12144. });
  12145. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12146. /**
  12147. * Gets a boolean indicating that the engine supports uniform buffers
  12148. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12149. */
  12150. get: function () {
  12151. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12157. /**
  12158. * Gets a boolean indicating that only power of 2 textures are supported
  12159. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12160. */
  12161. get: function () {
  12162. return this._webGLVersion < 2 || this.forcePOTTextures;
  12163. },
  12164. enumerable: true,
  12165. configurable: true
  12166. });
  12167. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12168. /**
  12169. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12170. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12171. */
  12172. get: function () {
  12173. return this._doNotHandleContextLost;
  12174. },
  12175. set: function (value) {
  12176. this._doNotHandleContextLost = value;
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12182. /**
  12183. * Gets the performance monitor attached to this engine
  12184. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12185. */
  12186. get: function () {
  12187. return this._performanceMonitor;
  12188. },
  12189. enumerable: true,
  12190. configurable: true
  12191. });
  12192. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12193. /**
  12194. * Gets the list of texture formats supported
  12195. */
  12196. get: function () {
  12197. return this._texturesSupported;
  12198. },
  12199. enumerable: true,
  12200. configurable: true
  12201. });
  12202. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12203. /**
  12204. * Gets the list of texture formats in use
  12205. */
  12206. get: function () {
  12207. return this._textureFormatInUse;
  12208. },
  12209. enumerable: true,
  12210. configurable: true
  12211. });
  12212. Object.defineProperty(Engine.prototype, "currentViewport", {
  12213. /**
  12214. * Gets the current viewport
  12215. */
  12216. get: function () {
  12217. return this._cachedViewport;
  12218. },
  12219. enumerable: true,
  12220. configurable: true
  12221. });
  12222. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12223. /**
  12224. * Gets the default empty texture
  12225. */
  12226. get: function () {
  12227. if (!this._emptyTexture) {
  12228. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12229. }
  12230. return this._emptyTexture;
  12231. },
  12232. enumerable: true,
  12233. configurable: true
  12234. });
  12235. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12236. /**
  12237. * Gets the default empty 3D texture
  12238. */
  12239. get: function () {
  12240. if (!this._emptyTexture3D) {
  12241. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12242. }
  12243. return this._emptyTexture3D;
  12244. },
  12245. enumerable: true,
  12246. configurable: true
  12247. });
  12248. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12249. /**
  12250. * Gets the default empty cube texture
  12251. */
  12252. get: function () {
  12253. if (!this._emptyCubeTexture) {
  12254. var faceData = new Uint8Array(4);
  12255. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12256. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12257. }
  12258. return this._emptyCubeTexture;
  12259. },
  12260. enumerable: true,
  12261. configurable: true
  12262. });
  12263. Engine.prototype._rebuildInternalTextures = function () {
  12264. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12265. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12266. var internalTexture = currentState_1[_i];
  12267. internalTexture._rebuild();
  12268. }
  12269. };
  12270. Engine.prototype._rebuildEffects = function () {
  12271. for (var key in this._compiledEffects) {
  12272. var effect = this._compiledEffects[key];
  12273. effect._prepareEffect();
  12274. }
  12275. BABYLON.Effect.ResetCache();
  12276. };
  12277. Engine.prototype._rebuildBuffers = function () {
  12278. // Index / Vertex
  12279. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12280. var scene = _a[_i];
  12281. scene.resetCachedMaterial();
  12282. scene._rebuildGeometries();
  12283. scene._rebuildTextures();
  12284. }
  12285. // Uniforms
  12286. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12287. var uniformBuffer = _c[_b];
  12288. uniformBuffer._rebuild();
  12289. }
  12290. };
  12291. Engine.prototype._initGLContext = function () {
  12292. // Caps
  12293. this._caps = new EngineCapabilities();
  12294. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12295. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12296. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12297. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12298. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12299. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12300. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12301. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12302. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12303. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12304. // Infos
  12305. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12306. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12307. if (rendererInfo != null) {
  12308. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12309. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12310. }
  12311. if (!this._glVendor) {
  12312. this._glVendor = "Unknown vendor";
  12313. }
  12314. if (!this._glRenderer) {
  12315. this._glRenderer = "Unknown renderer";
  12316. }
  12317. // Constants
  12318. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12319. if (this._gl.RGBA16F !== 0x881A) {
  12320. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12321. }
  12322. if (this._gl.RGBA32F !== 0x8814) {
  12323. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12324. }
  12325. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12326. this._gl.DEPTH24_STENCIL8 = 35056;
  12327. }
  12328. // Extensions
  12329. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12330. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12331. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12332. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12333. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12334. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12335. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12336. 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');
  12337. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12338. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12339. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12340. this._caps.highPrecisionShaderSupported = true;
  12341. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12342. if (this._caps.timerQuery) {
  12343. if (this._webGLVersion === 1) {
  12344. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12345. }
  12346. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12347. }
  12348. // Checks if some of the format renders first to allow the use of webgl inspector.
  12349. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12350. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12351. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12352. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12353. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12354. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12355. if (this._webGLVersion > 1) {
  12356. this._gl.HALF_FLOAT_OES = 0x140B;
  12357. }
  12358. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12359. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12360. // Draw buffers
  12361. if (this._webGLVersion > 1) {
  12362. this._caps.drawBuffersExtension = true;
  12363. }
  12364. else {
  12365. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12366. if (drawBuffersExtension !== null) {
  12367. this._caps.drawBuffersExtension = true;
  12368. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12369. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12370. for (var i = 0; i < 16; i++) {
  12371. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12372. }
  12373. }
  12374. else {
  12375. this._caps.drawBuffersExtension = false;
  12376. }
  12377. }
  12378. // Depth Texture
  12379. if (this._webGLVersion > 1) {
  12380. this._caps.depthTextureExtension = true;
  12381. }
  12382. else {
  12383. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12384. if (depthTextureExtension != null) {
  12385. this._caps.depthTextureExtension = true;
  12386. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12387. }
  12388. }
  12389. // Vertex array object
  12390. if (this._webGLVersion > 1) {
  12391. this._caps.vertexArrayObject = true;
  12392. }
  12393. else {
  12394. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12395. if (vertexArrayObjectExtension != null) {
  12396. this._caps.vertexArrayObject = true;
  12397. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12398. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12399. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12400. }
  12401. else {
  12402. this._caps.vertexArrayObject = false;
  12403. }
  12404. }
  12405. // Instances count
  12406. if (this._webGLVersion > 1) {
  12407. this._caps.instancedArrays = true;
  12408. }
  12409. else {
  12410. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12411. if (instanceExtension != null) {
  12412. this._caps.instancedArrays = true;
  12413. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12414. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12415. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12416. }
  12417. else {
  12418. this._caps.instancedArrays = false;
  12419. }
  12420. }
  12421. // Intelligently add supported compressed formats in order to check for.
  12422. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12423. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12424. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12425. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12426. if (this._caps.astc)
  12427. this.texturesSupported.push('-astc.ktx');
  12428. if (this._caps.s3tc)
  12429. this.texturesSupported.push('-dxt.ktx');
  12430. if (this._caps.pvrtc)
  12431. this.texturesSupported.push('-pvrtc.ktx');
  12432. if (this._caps.etc2)
  12433. this.texturesSupported.push('-etc2.ktx');
  12434. if (this._caps.etc1)
  12435. this.texturesSupported.push('-etc1.ktx');
  12436. if (this._gl.getShaderPrecisionFormat) {
  12437. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12438. if (highp) {
  12439. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12440. }
  12441. }
  12442. // Depth buffer
  12443. this.setDepthBuffer(true);
  12444. this.setDepthFunctionToLessOrEqual();
  12445. this.setDepthWrite(true);
  12446. // Texture maps
  12447. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12448. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12449. this._nextFreeTextureSlots.push(slot);
  12450. }
  12451. };
  12452. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12453. /**
  12454. * Gets version of the current webGL context
  12455. */
  12456. get: function () {
  12457. return this._webGLVersion;
  12458. },
  12459. enumerable: true,
  12460. configurable: true
  12461. });
  12462. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12463. /**
  12464. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12465. */
  12466. get: function () {
  12467. return this._isStencilEnable;
  12468. },
  12469. enumerable: true,
  12470. configurable: true
  12471. });
  12472. Engine.prototype._prepareWorkingCanvas = function () {
  12473. if (this._workingCanvas) {
  12474. return;
  12475. }
  12476. this._workingCanvas = document.createElement("canvas");
  12477. var context = this._workingCanvas.getContext("2d");
  12478. if (context) {
  12479. this._workingContext = context;
  12480. }
  12481. };
  12482. /**
  12483. * Reset the texture cache to empty state
  12484. */
  12485. Engine.prototype.resetTextureCache = function () {
  12486. for (var key in this._boundTexturesCache) {
  12487. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12488. continue;
  12489. }
  12490. var boundTexture = this._boundTexturesCache[key];
  12491. if (boundTexture) {
  12492. this._removeDesignatedSlot(boundTexture);
  12493. }
  12494. this._boundTexturesCache[key] = null;
  12495. }
  12496. if (!this.disableTextureBindingOptimization) {
  12497. this._nextFreeTextureSlots = [];
  12498. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12499. this._nextFreeTextureSlots.push(slot);
  12500. }
  12501. }
  12502. this._currentTextureChannel = -1;
  12503. };
  12504. /**
  12505. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12506. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12507. * @returns true if engine is in deterministic lock step mode
  12508. */
  12509. Engine.prototype.isDeterministicLockStep = function () {
  12510. return this._deterministicLockstep;
  12511. };
  12512. /**
  12513. * Gets the max steps when engine is running in deterministic lock step
  12514. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12515. * @returns the max steps
  12516. */
  12517. Engine.prototype.getLockstepMaxSteps = function () {
  12518. return this._lockstepMaxSteps;
  12519. };
  12520. /**
  12521. * Gets an object containing information about the current webGL context
  12522. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12523. */
  12524. Engine.prototype.getGlInfo = function () {
  12525. return {
  12526. vendor: this._glVendor,
  12527. renderer: this._glRenderer,
  12528. version: this._glVersion
  12529. };
  12530. };
  12531. /**
  12532. * Gets current aspect ratio
  12533. * @param camera defines the camera to use to get the aspect ratio
  12534. * @param useScreen defines if screen size must be used (or the current render target if any)
  12535. * @returns a number defining the aspect ratio
  12536. */
  12537. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12538. if (useScreen === void 0) { useScreen = false; }
  12539. var viewport = camera.viewport;
  12540. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12541. };
  12542. /**
  12543. * Gets current screen aspect ratio
  12544. * @returns a number defining the aspect ratio
  12545. */
  12546. Engine.prototype.getScreenAspectRatio = function () {
  12547. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12548. };
  12549. /**
  12550. * Gets the current render width
  12551. * @param useScreen defines if screen size must be used (or the current render target if any)
  12552. * @returns a number defining the current render width
  12553. */
  12554. Engine.prototype.getRenderWidth = function (useScreen) {
  12555. if (useScreen === void 0) { useScreen = false; }
  12556. if (!useScreen && this._currentRenderTarget) {
  12557. return this._currentRenderTarget.width;
  12558. }
  12559. return this._gl.drawingBufferWidth;
  12560. };
  12561. /**
  12562. * Gets the current render height
  12563. * @param useScreen defines if screen size must be used (or the current render target if any)
  12564. * @returns a number defining the current render height
  12565. */
  12566. Engine.prototype.getRenderHeight = function (useScreen) {
  12567. if (useScreen === void 0) { useScreen = false; }
  12568. if (!useScreen && this._currentRenderTarget) {
  12569. return this._currentRenderTarget.height;
  12570. }
  12571. return this._gl.drawingBufferHeight;
  12572. };
  12573. /**
  12574. * Gets the HTML canvas attached with the current webGL context
  12575. * @returns a HTML canvas
  12576. */
  12577. Engine.prototype.getRenderingCanvas = function () {
  12578. return this._renderingCanvas;
  12579. };
  12580. /**
  12581. * Gets the client rect of the HTML canvas attached with the current webGL context
  12582. * @returns a client rectanglee
  12583. */
  12584. Engine.prototype.getRenderingCanvasClientRect = function () {
  12585. if (!this._renderingCanvas) {
  12586. return null;
  12587. }
  12588. return this._renderingCanvas.getBoundingClientRect();
  12589. };
  12590. /**
  12591. * Defines the hardware scaling level.
  12592. * By default the hardware scaling level is computed from the window device ratio.
  12593. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12594. * @param level defines the level to use
  12595. */
  12596. Engine.prototype.setHardwareScalingLevel = function (level) {
  12597. this._hardwareScalingLevel = level;
  12598. this.resize();
  12599. };
  12600. /**
  12601. * Gets the current hardware scaling level.
  12602. * By default the hardware scaling level is computed from the window device ratio.
  12603. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12604. * @returns a number indicating the current hardware scaling level
  12605. */
  12606. Engine.prototype.getHardwareScalingLevel = function () {
  12607. return this._hardwareScalingLevel;
  12608. };
  12609. /**
  12610. * Gets the list of loaded textures
  12611. * @returns an array containing all loaded textures
  12612. */
  12613. Engine.prototype.getLoadedTexturesCache = function () {
  12614. return this._internalTexturesCache;
  12615. };
  12616. /**
  12617. * Gets the object containing all engine capabilities
  12618. * @returns the EngineCapabilities object
  12619. */
  12620. Engine.prototype.getCaps = function () {
  12621. return this._caps;
  12622. };
  12623. Object.defineProperty(Engine.prototype, "drawCalls", {
  12624. /** @hidden */
  12625. get: function () {
  12626. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12627. return 0;
  12628. },
  12629. enumerable: true,
  12630. configurable: true
  12631. });
  12632. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12633. /** @hidden */
  12634. get: function () {
  12635. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12636. return null;
  12637. },
  12638. enumerable: true,
  12639. configurable: true
  12640. });
  12641. /**
  12642. * Gets the current depth function
  12643. * @returns a number defining the depth function
  12644. */
  12645. Engine.prototype.getDepthFunction = function () {
  12646. return this._depthCullingState.depthFunc;
  12647. };
  12648. /**
  12649. * Sets the current depth function
  12650. * @param depthFunc defines the function to use
  12651. */
  12652. Engine.prototype.setDepthFunction = function (depthFunc) {
  12653. this._depthCullingState.depthFunc = depthFunc;
  12654. };
  12655. /**
  12656. * Sets the current depth function to GREATER
  12657. */
  12658. Engine.prototype.setDepthFunctionToGreater = function () {
  12659. this._depthCullingState.depthFunc = this._gl.GREATER;
  12660. };
  12661. /**
  12662. * Sets the current depth function to GEQUAL
  12663. */
  12664. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12665. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12666. };
  12667. /**
  12668. * Sets the current depth function to LESS
  12669. */
  12670. Engine.prototype.setDepthFunctionToLess = function () {
  12671. this._depthCullingState.depthFunc = this._gl.LESS;
  12672. };
  12673. /**
  12674. * Sets the current depth function to LEQUAL
  12675. */
  12676. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12677. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12678. };
  12679. /**
  12680. * Gets a boolean indicating if stencil buffer is enabled
  12681. * @returns the current stencil buffer state
  12682. */
  12683. Engine.prototype.getStencilBuffer = function () {
  12684. return this._stencilState.stencilTest;
  12685. };
  12686. /**
  12687. * Enable or disable the stencil buffer
  12688. * @param enable defines if the stencil buffer must be enabled or disabled
  12689. */
  12690. Engine.prototype.setStencilBuffer = function (enable) {
  12691. this._stencilState.stencilTest = enable;
  12692. };
  12693. /**
  12694. * Gets the current stencil mask
  12695. * @returns a number defining the new stencil mask to use
  12696. */
  12697. Engine.prototype.getStencilMask = function () {
  12698. return this._stencilState.stencilMask;
  12699. };
  12700. /**
  12701. * Sets the current stencil mask
  12702. * @param mask defines the new stencil mask to use
  12703. */
  12704. Engine.prototype.setStencilMask = function (mask) {
  12705. this._stencilState.stencilMask = mask;
  12706. };
  12707. /**
  12708. * Gets the current stencil function
  12709. * @returns a number defining the stencil function to use
  12710. */
  12711. Engine.prototype.getStencilFunction = function () {
  12712. return this._stencilState.stencilFunc;
  12713. };
  12714. /**
  12715. * Gets the current stencil reference value
  12716. * @returns a number defining the stencil reference value to use
  12717. */
  12718. Engine.prototype.getStencilFunctionReference = function () {
  12719. return this._stencilState.stencilFuncRef;
  12720. };
  12721. /**
  12722. * Gets the current stencil mask
  12723. * @returns a number defining the stencil mask to use
  12724. */
  12725. Engine.prototype.getStencilFunctionMask = function () {
  12726. return this._stencilState.stencilFuncMask;
  12727. };
  12728. /**
  12729. * Sets the current stencil function
  12730. * @param stencilFunc defines the new stencil function to use
  12731. */
  12732. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12733. this._stencilState.stencilFunc = stencilFunc;
  12734. };
  12735. /**
  12736. * Sets the current stencil reference
  12737. * @param reference defines the new stencil reference to use
  12738. */
  12739. Engine.prototype.setStencilFunctionReference = function (reference) {
  12740. this._stencilState.stencilFuncRef = reference;
  12741. };
  12742. /**
  12743. * Sets the current stencil mask
  12744. * @param mask defines the new stencil mask to use
  12745. */
  12746. Engine.prototype.setStencilFunctionMask = function (mask) {
  12747. this._stencilState.stencilFuncMask = mask;
  12748. };
  12749. /**
  12750. * Gets the current stencil operation when stencil fails
  12751. * @returns a number defining stencil operation to use when stencil fails
  12752. */
  12753. Engine.prototype.getStencilOperationFail = function () {
  12754. return this._stencilState.stencilOpStencilFail;
  12755. };
  12756. /**
  12757. * Gets the current stencil operation when depth fails
  12758. * @returns a number defining stencil operation to use when depth fails
  12759. */
  12760. Engine.prototype.getStencilOperationDepthFail = function () {
  12761. return this._stencilState.stencilOpDepthFail;
  12762. };
  12763. /**
  12764. * Gets the current stencil operation when stencil passes
  12765. * @returns a number defining stencil operation to use when stencil passes
  12766. */
  12767. Engine.prototype.getStencilOperationPass = function () {
  12768. return this._stencilState.stencilOpStencilDepthPass;
  12769. };
  12770. /**
  12771. * Sets the stencil operation to use when stencil fails
  12772. * @param operation defines the stencil operation to use when stencil fails
  12773. */
  12774. Engine.prototype.setStencilOperationFail = function (operation) {
  12775. this._stencilState.stencilOpStencilFail = operation;
  12776. };
  12777. /**
  12778. * Sets the stencil operation to use when depth fails
  12779. * @param operation defines the stencil operation to use when depth fails
  12780. */
  12781. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12782. this._stencilState.stencilOpDepthFail = operation;
  12783. };
  12784. /**
  12785. * Sets the stencil operation to use when stencil passes
  12786. * @param operation defines the stencil operation to use when stencil passes
  12787. */
  12788. Engine.prototype.setStencilOperationPass = function (operation) {
  12789. this._stencilState.stencilOpStencilDepthPass = operation;
  12790. };
  12791. /**
  12792. * Sets a boolean indicating if the dithering state is enabled or disabled
  12793. * @param value defines the dithering state
  12794. */
  12795. Engine.prototype.setDitheringState = function (value) {
  12796. if (value) {
  12797. this._gl.enable(this._gl.DITHER);
  12798. }
  12799. else {
  12800. this._gl.disable(this._gl.DITHER);
  12801. }
  12802. };
  12803. /**
  12804. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12805. * @param value defines the rasterizer state
  12806. */
  12807. Engine.prototype.setRasterizerState = function (value) {
  12808. if (value) {
  12809. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12810. }
  12811. else {
  12812. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12813. }
  12814. };
  12815. /**
  12816. * stop executing a render loop function and remove it from the execution array
  12817. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12818. */
  12819. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12820. if (!renderFunction) {
  12821. this._activeRenderLoops = [];
  12822. return;
  12823. }
  12824. var index = this._activeRenderLoops.indexOf(renderFunction);
  12825. if (index >= 0) {
  12826. this._activeRenderLoops.splice(index, 1);
  12827. }
  12828. };
  12829. /** @hidden */
  12830. Engine.prototype._renderLoop = function () {
  12831. if (!this._contextWasLost) {
  12832. var shouldRender = true;
  12833. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12834. shouldRender = false;
  12835. }
  12836. if (shouldRender) {
  12837. // Start new frame
  12838. this.beginFrame();
  12839. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12840. var renderFunction = this._activeRenderLoops[index];
  12841. renderFunction();
  12842. }
  12843. // Present
  12844. this.endFrame();
  12845. }
  12846. }
  12847. if (this._activeRenderLoops.length > 0) {
  12848. // Register new frame
  12849. var requester = null;
  12850. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12851. requester = this._vrDisplay;
  12852. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12853. }
  12854. else {
  12855. this._renderingQueueLaunched = false;
  12856. }
  12857. };
  12858. /**
  12859. * Register and execute a render loop. The engine can have more than one render function
  12860. * @param renderFunction defines the function to continuously execute
  12861. */
  12862. Engine.prototype.runRenderLoop = function (renderFunction) {
  12863. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12864. return;
  12865. }
  12866. this._activeRenderLoops.push(renderFunction);
  12867. if (!this._renderingQueueLaunched) {
  12868. this._renderingQueueLaunched = true;
  12869. this._bindedRenderFunction = this._renderLoop.bind(this);
  12870. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12871. }
  12872. };
  12873. /**
  12874. * Toggle full screen mode
  12875. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12876. * @param options defines an option object to be sent to the requestFullscreen function
  12877. */
  12878. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12879. if (this.isFullscreen) {
  12880. BABYLON.Tools.ExitFullscreen();
  12881. }
  12882. else {
  12883. this._pointerLockRequested = requestPointerLock;
  12884. if (this._renderingCanvas) {
  12885. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12886. }
  12887. }
  12888. };
  12889. /**
  12890. * Clear the current render buffer or the current render target (if any is set up)
  12891. * @param color defines the color to use
  12892. * @param backBuffer defines if the back buffer must be cleared
  12893. * @param depth defines if the depth buffer must be cleared
  12894. * @param stencil defines if the stencil buffer must be cleared
  12895. */
  12896. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12897. if (stencil === void 0) { stencil = false; }
  12898. this.applyStates();
  12899. var mode = 0;
  12900. if (backBuffer && color) {
  12901. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12902. mode |= this._gl.COLOR_BUFFER_BIT;
  12903. }
  12904. if (depth) {
  12905. this._gl.clearDepth(1.0);
  12906. mode |= this._gl.DEPTH_BUFFER_BIT;
  12907. }
  12908. if (stencil) {
  12909. this._gl.clearStencil(0);
  12910. mode |= this._gl.STENCIL_BUFFER_BIT;
  12911. }
  12912. this._gl.clear(mode);
  12913. };
  12914. /**
  12915. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12916. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12917. * @param y defines the y-coordinate of the corner of the clear rectangle
  12918. * @param width defines the width of the clear rectangle
  12919. * @param height defines the height of the clear rectangle
  12920. * @param clearColor defines the clear color
  12921. */
  12922. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12923. var gl = this._gl;
  12924. // Save state
  12925. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12926. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12927. // Change state
  12928. gl.enable(gl.SCISSOR_TEST);
  12929. gl.scissor(x, y, width, height);
  12930. // Clear
  12931. this.clear(clearColor, true, true, true);
  12932. // Restore state
  12933. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12934. if (curScissor === true) {
  12935. gl.enable(gl.SCISSOR_TEST);
  12936. }
  12937. else {
  12938. gl.disable(gl.SCISSOR_TEST);
  12939. }
  12940. };
  12941. /** @hidden */
  12942. Engine.prototype._viewport = function (x, y, width, height) {
  12943. if (x !== this._viewportCached.x ||
  12944. y !== this._viewportCached.y ||
  12945. width !== this._viewportCached.z ||
  12946. height !== this._viewportCached.w) {
  12947. this._viewportCached.x = x;
  12948. this._viewportCached.y = y;
  12949. this._viewportCached.z = width;
  12950. this._viewportCached.w = height;
  12951. this._gl.viewport(x, y, width, height);
  12952. }
  12953. };
  12954. /**
  12955. * Set the WebGL's viewport
  12956. * @param viewport defines the viewport element to be used
  12957. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12958. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12959. */
  12960. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12961. var width = requiredWidth || this.getRenderWidth();
  12962. var height = requiredHeight || this.getRenderHeight();
  12963. var x = viewport.x || 0;
  12964. var y = viewport.y || 0;
  12965. this._cachedViewport = viewport;
  12966. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12967. };
  12968. /**
  12969. * Directly set the WebGL Viewport
  12970. * @param x defines the x coordinate of the viewport (in screen space)
  12971. * @param y defines the y coordinate of the viewport (in screen space)
  12972. * @param width defines the width of the viewport (in screen space)
  12973. * @param height defines the height of the viewport (in screen space)
  12974. * @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
  12975. */
  12976. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12977. var currentViewport = this._cachedViewport;
  12978. this._cachedViewport = null;
  12979. this._viewport(x, y, width, height);
  12980. return currentViewport;
  12981. };
  12982. /**
  12983. * Begin a new frame
  12984. */
  12985. Engine.prototype.beginFrame = function () {
  12986. this.onBeginFrameObservable.notifyObservers(this);
  12987. this._measureFps();
  12988. };
  12989. /**
  12990. * Enf the current frame
  12991. */
  12992. Engine.prototype.endFrame = function () {
  12993. // Force a flush in case we are using a bad OS.
  12994. if (this._badOS) {
  12995. this.flushFramebuffer();
  12996. }
  12997. // Submit frame to the vr device, if enabled
  12998. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12999. // TODO: We should only submit the frame if we read frameData successfully.
  13000. this._vrDisplay.submitFrame();
  13001. }
  13002. this.onEndFrameObservable.notifyObservers(this);
  13003. };
  13004. /**
  13005. * Resize the view according to the canvas' size
  13006. */
  13007. Engine.prototype.resize = function () {
  13008. // We're not resizing the size of the canvas while in VR mode & presenting
  13009. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13010. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13011. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13012. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13013. }
  13014. };
  13015. /**
  13016. * Force a specific size of the canvas
  13017. * @param width defines the new canvas' width
  13018. * @param height defines the new canvas' height
  13019. */
  13020. Engine.prototype.setSize = function (width, height) {
  13021. if (!this._renderingCanvas) {
  13022. return;
  13023. }
  13024. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13025. return;
  13026. }
  13027. this._renderingCanvas.width = width;
  13028. this._renderingCanvas.height = height;
  13029. for (var index = 0; index < this.scenes.length; index++) {
  13030. var scene = this.scenes[index];
  13031. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13032. var cam = scene.cameras[camIndex];
  13033. cam._currentRenderId = 0;
  13034. }
  13035. }
  13036. if (this.onResizeObservable.hasObservers) {
  13037. this.onResizeObservable.notifyObservers(this);
  13038. }
  13039. };
  13040. // WebVR functions
  13041. /**
  13042. * Gets a boolean indicating if a webVR device was detected
  13043. * @returns true if a webVR device was detected
  13044. */
  13045. Engine.prototype.isVRDevicePresent = function () {
  13046. return !!this._vrDisplay;
  13047. };
  13048. /**
  13049. * Gets the current webVR device
  13050. * @returns the current webVR device (or null)
  13051. */
  13052. Engine.prototype.getVRDevice = function () {
  13053. return this._vrDisplay;
  13054. };
  13055. /**
  13056. * Initializes a webVR display and starts listening to display change events
  13057. * The onVRDisplayChangedObservable will be notified upon these changes
  13058. * @returns The onVRDisplayChangedObservable
  13059. */
  13060. Engine.prototype.initWebVR = function () {
  13061. this.initWebVRAsync();
  13062. return this.onVRDisplayChangedObservable;
  13063. };
  13064. /**
  13065. * Initializes a webVR display and starts listening to display change events
  13066. * The onVRDisplayChangedObservable will be notified upon these changes
  13067. * @returns A promise containing a VRDisplay and if vr is supported
  13068. */
  13069. Engine.prototype.initWebVRAsync = function () {
  13070. var _this = this;
  13071. var notifyObservers = function () {
  13072. var eventArgs = {
  13073. vrDisplay: _this._vrDisplay,
  13074. vrSupported: _this._vrSupported
  13075. };
  13076. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13077. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13078. };
  13079. if (!this._onVrDisplayConnect) {
  13080. this._onVrDisplayConnect = function (event) {
  13081. _this._vrDisplay = event.display;
  13082. notifyObservers();
  13083. };
  13084. this._onVrDisplayDisconnect = function () {
  13085. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13086. _this._vrDisplay = undefined;
  13087. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13088. notifyObservers();
  13089. };
  13090. this._onVrDisplayPresentChange = function () {
  13091. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13092. };
  13093. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13094. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13095. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13096. }
  13097. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13098. this._webVRInitPromise.then(notifyObservers);
  13099. return this._webVRInitPromise;
  13100. };
  13101. /**
  13102. * Call this function to switch to webVR mode
  13103. * Will do nothing if webVR is not supported or if there is no webVR device
  13104. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13105. */
  13106. Engine.prototype.enableVR = function () {
  13107. var _this = this;
  13108. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13109. var onResolved = function () {
  13110. _this.onVRRequestPresentComplete.notifyObservers(true);
  13111. _this._onVRFullScreenTriggered();
  13112. };
  13113. var onRejected = function () {
  13114. _this.onVRRequestPresentComplete.notifyObservers(false);
  13115. };
  13116. this.onVRRequestPresentStart.notifyObservers(this);
  13117. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13118. }
  13119. };
  13120. /**
  13121. * Call this function to leave webVR mode
  13122. * Will do nothing if webVR is not supported or if there is no webVR device
  13123. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13124. */
  13125. Engine.prototype.disableVR = function () {
  13126. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13127. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13128. }
  13129. };
  13130. Engine.prototype._getVRDisplaysAsync = function () {
  13131. var _this = this;
  13132. return new Promise(function (res, rej) {
  13133. if (navigator.getVRDisplays) {
  13134. navigator.getVRDisplays().then(function (devices) {
  13135. _this._vrSupported = true;
  13136. // note that devices may actually be an empty array. This is fine;
  13137. // we expect this._vrDisplay to be undefined in this case.
  13138. _this._vrDisplay = devices[0];
  13139. res({
  13140. vrDisplay: _this._vrDisplay,
  13141. vrSupported: _this._vrSupported
  13142. });
  13143. });
  13144. }
  13145. else {
  13146. _this._vrDisplay = undefined;
  13147. _this._vrSupported = false;
  13148. res({
  13149. vrDisplay: _this._vrDisplay,
  13150. vrSupported: _this._vrSupported
  13151. });
  13152. }
  13153. });
  13154. };
  13155. /**
  13156. * Binds the frame buffer to the specified texture.
  13157. * @param texture The texture to render to or null for the default canvas
  13158. * @param faceIndex The face of the texture to render to in case of cube texture
  13159. * @param requiredWidth The width of the target to render to
  13160. * @param requiredHeight The height of the target to render to
  13161. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13162. * @param depthStencilTexture The depth stencil texture to use to render
  13163. * @param lodLevel defines le lod level to bind to the frame buffer
  13164. */
  13165. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13166. if (lodLevel === void 0) { lodLevel = 0; }
  13167. if (this._currentRenderTarget) {
  13168. this.unBindFramebuffer(this._currentRenderTarget);
  13169. }
  13170. this._currentRenderTarget = texture;
  13171. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13172. var gl = this._gl;
  13173. if (texture.isCube) {
  13174. if (faceIndex === undefined) {
  13175. faceIndex = 0;
  13176. }
  13177. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13178. if (depthStencilTexture) {
  13179. if (depthStencilTexture._generateStencilBuffer) {
  13180. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13181. }
  13182. else {
  13183. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13184. }
  13185. }
  13186. }
  13187. if (this._cachedViewport && !forceFullscreenViewport) {
  13188. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13189. }
  13190. else {
  13191. if (!requiredWidth) {
  13192. requiredWidth = texture.width;
  13193. if (lodLevel) {
  13194. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13195. }
  13196. }
  13197. if (!requiredHeight) {
  13198. requiredHeight = texture.height;
  13199. if (lodLevel) {
  13200. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13201. }
  13202. }
  13203. this._viewport(0, 0, requiredWidth, requiredHeight);
  13204. }
  13205. this.wipeCaches();
  13206. };
  13207. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13208. if (this._currentFramebuffer !== framebuffer) {
  13209. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13210. this._currentFramebuffer = framebuffer;
  13211. }
  13212. };
  13213. /**
  13214. * Unbind the current render target texture from the webGL context
  13215. * @param texture defines the render target texture to unbind
  13216. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13217. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13218. */
  13219. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13220. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13221. this._currentRenderTarget = null;
  13222. // If MSAA, we need to bitblt back to main texture
  13223. var gl = this._gl;
  13224. if (texture._MSAAFramebuffer) {
  13225. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13226. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13227. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13228. }
  13229. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13230. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13231. gl.generateMipmap(gl.TEXTURE_2D);
  13232. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13233. }
  13234. if (onBeforeUnbind) {
  13235. if (texture._MSAAFramebuffer) {
  13236. // Bind the correct framebuffer
  13237. this.bindUnboundFramebuffer(texture._framebuffer);
  13238. }
  13239. onBeforeUnbind();
  13240. }
  13241. this.bindUnboundFramebuffer(null);
  13242. };
  13243. /**
  13244. * Unbind a list of render target textures from the webGL context
  13245. * This is used only when drawBuffer extension or webGL2 are active
  13246. * @param textures defines the render target textures to unbind
  13247. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13248. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13249. */
  13250. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13251. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13252. this._currentRenderTarget = null;
  13253. // If MSAA, we need to bitblt back to main texture
  13254. var gl = this._gl;
  13255. if (textures[0]._MSAAFramebuffer) {
  13256. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13257. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13258. var attachments = textures[0]._attachments;
  13259. if (!attachments) {
  13260. attachments = new Array(textures.length);
  13261. textures[0]._attachments = attachments;
  13262. }
  13263. for (var i = 0; i < textures.length; i++) {
  13264. var texture = textures[i];
  13265. for (var j = 0; j < attachments.length; j++) {
  13266. attachments[j] = gl.NONE;
  13267. }
  13268. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13269. gl.readBuffer(attachments[i]);
  13270. gl.drawBuffers(attachments);
  13271. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13272. }
  13273. for (var i = 0; i < attachments.length; i++) {
  13274. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13275. }
  13276. gl.drawBuffers(attachments);
  13277. }
  13278. for (var i = 0; i < textures.length; i++) {
  13279. var texture = textures[i];
  13280. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13281. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13282. gl.generateMipmap(gl.TEXTURE_2D);
  13283. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13284. }
  13285. }
  13286. if (onBeforeUnbind) {
  13287. if (textures[0]._MSAAFramebuffer) {
  13288. // Bind the correct framebuffer
  13289. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13290. }
  13291. onBeforeUnbind();
  13292. }
  13293. this.bindUnboundFramebuffer(null);
  13294. };
  13295. /**
  13296. * Force the mipmap generation for the given render target texture
  13297. * @param texture defines the render target texture to use
  13298. */
  13299. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13300. if (texture.generateMipMaps) {
  13301. var gl = this._gl;
  13302. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13303. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13304. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13305. }
  13306. };
  13307. /**
  13308. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13309. */
  13310. Engine.prototype.flushFramebuffer = function () {
  13311. this._gl.flush();
  13312. };
  13313. /**
  13314. * Unbind the current render target and bind the default framebuffer
  13315. */
  13316. Engine.prototype.restoreDefaultFramebuffer = function () {
  13317. if (this._currentRenderTarget) {
  13318. this.unBindFramebuffer(this._currentRenderTarget);
  13319. }
  13320. else {
  13321. this.bindUnboundFramebuffer(null);
  13322. }
  13323. if (this._cachedViewport) {
  13324. this.setViewport(this._cachedViewport);
  13325. }
  13326. this.wipeCaches();
  13327. };
  13328. // UBOs
  13329. /**
  13330. * Create an uniform buffer
  13331. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13332. * @param elements defines the content of the uniform buffer
  13333. * @returns the webGL uniform buffer
  13334. */
  13335. Engine.prototype.createUniformBuffer = function (elements) {
  13336. var ubo = this._gl.createBuffer();
  13337. if (!ubo) {
  13338. throw new Error("Unable to create uniform buffer");
  13339. }
  13340. this.bindUniformBuffer(ubo);
  13341. if (elements instanceof Float32Array) {
  13342. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13343. }
  13344. else {
  13345. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13346. }
  13347. this.bindUniformBuffer(null);
  13348. ubo.references = 1;
  13349. return ubo;
  13350. };
  13351. /**
  13352. * Create a dynamic uniform buffer
  13353. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13354. * @param elements defines the content of the uniform buffer
  13355. * @returns the webGL uniform buffer
  13356. */
  13357. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13358. var ubo = this._gl.createBuffer();
  13359. if (!ubo) {
  13360. throw new Error("Unable to create dynamic uniform buffer");
  13361. }
  13362. this.bindUniformBuffer(ubo);
  13363. if (elements instanceof Float32Array) {
  13364. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13365. }
  13366. else {
  13367. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13368. }
  13369. this.bindUniformBuffer(null);
  13370. ubo.references = 1;
  13371. return ubo;
  13372. };
  13373. /**
  13374. * Update an existing uniform buffer
  13375. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13376. * @param uniformBuffer defines the target uniform buffer
  13377. * @param elements defines the content to update
  13378. * @param offset defines the offset in the uniform buffer where update should start
  13379. * @param count defines the size of the data to update
  13380. */
  13381. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13382. this.bindUniformBuffer(uniformBuffer);
  13383. if (offset === undefined) {
  13384. offset = 0;
  13385. }
  13386. if (count === undefined) {
  13387. if (elements instanceof Float32Array) {
  13388. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13389. }
  13390. else {
  13391. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13392. }
  13393. }
  13394. else {
  13395. if (elements instanceof Float32Array) {
  13396. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13397. }
  13398. else {
  13399. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13400. }
  13401. }
  13402. this.bindUniformBuffer(null);
  13403. };
  13404. // VBOs
  13405. Engine.prototype._resetVertexBufferBinding = function () {
  13406. this.bindArrayBuffer(null);
  13407. this._cachedVertexBuffers = null;
  13408. };
  13409. /**
  13410. * Creates a vertex buffer
  13411. * @param data the data for the vertex buffer
  13412. * @returns the new WebGL static buffer
  13413. */
  13414. Engine.prototype.createVertexBuffer = function (data) {
  13415. var vbo = this._gl.createBuffer();
  13416. if (!vbo) {
  13417. throw new Error("Unable to create vertex buffer");
  13418. }
  13419. this.bindArrayBuffer(vbo);
  13420. if (data instanceof Array) {
  13421. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13422. }
  13423. else {
  13424. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13425. }
  13426. this._resetVertexBufferBinding();
  13427. vbo.references = 1;
  13428. return vbo;
  13429. };
  13430. /**
  13431. * Creates a dynamic vertex buffer
  13432. * @param data the data for the dynamic vertex buffer
  13433. * @returns the new WebGL dynamic buffer
  13434. */
  13435. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13436. var vbo = this._gl.createBuffer();
  13437. if (!vbo) {
  13438. throw new Error("Unable to create dynamic vertex buffer");
  13439. }
  13440. this.bindArrayBuffer(vbo);
  13441. if (data instanceof Array) {
  13442. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13443. }
  13444. else {
  13445. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13446. }
  13447. this._resetVertexBufferBinding();
  13448. vbo.references = 1;
  13449. return vbo;
  13450. };
  13451. /**
  13452. * Update a dynamic index buffer
  13453. * @param indexBuffer defines the target index buffer
  13454. * @param indices defines the data to update
  13455. * @param offset defines the offset in the target index buffer where update should start
  13456. */
  13457. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13458. if (offset === void 0) { offset = 0; }
  13459. // Force cache update
  13460. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13461. this.bindIndexBuffer(indexBuffer);
  13462. var arrayBuffer;
  13463. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13464. arrayBuffer = indices;
  13465. }
  13466. else {
  13467. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13468. }
  13469. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13470. this._resetIndexBufferBinding();
  13471. };
  13472. /**
  13473. * Updates a dynamic vertex buffer.
  13474. * @param vertexBuffer the vertex buffer to update
  13475. * @param data the data used to update the vertex buffer
  13476. * @param byteOffset the byte offset of the data
  13477. * @param byteLength the byte length of the data
  13478. */
  13479. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13480. this.bindArrayBuffer(vertexBuffer);
  13481. if (byteOffset === undefined) {
  13482. byteOffset = 0;
  13483. }
  13484. if (byteLength === undefined) {
  13485. if (data instanceof Array) {
  13486. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13487. }
  13488. else {
  13489. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13490. }
  13491. }
  13492. else {
  13493. if (data instanceof Array) {
  13494. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13495. }
  13496. else {
  13497. if (data instanceof ArrayBuffer) {
  13498. data = new Uint8Array(data, byteOffset, byteLength);
  13499. }
  13500. else {
  13501. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13502. }
  13503. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13504. }
  13505. }
  13506. this._resetVertexBufferBinding();
  13507. };
  13508. Engine.prototype._resetIndexBufferBinding = function () {
  13509. this.bindIndexBuffer(null);
  13510. this._cachedIndexBuffer = null;
  13511. };
  13512. /**
  13513. * Creates a new index buffer
  13514. * @param indices defines the content of the index buffer
  13515. * @param updatable defines if the index buffer must be updatable
  13516. * @returns a new webGL buffer
  13517. */
  13518. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13519. var vbo = this._gl.createBuffer();
  13520. if (!vbo) {
  13521. throw new Error("Unable to create index buffer");
  13522. }
  13523. this.bindIndexBuffer(vbo);
  13524. // Check for 32 bits indices
  13525. var arrayBuffer;
  13526. var need32Bits = false;
  13527. if (indices instanceof Uint16Array) {
  13528. arrayBuffer = indices;
  13529. }
  13530. else {
  13531. //check 32 bit support
  13532. if (this._caps.uintIndices) {
  13533. if (indices instanceof Uint32Array) {
  13534. arrayBuffer = indices;
  13535. need32Bits = true;
  13536. }
  13537. else {
  13538. //number[] or Int32Array, check if 32 bit is necessary
  13539. for (var index = 0; index < indices.length; index++) {
  13540. if (indices[index] > 65535) {
  13541. need32Bits = true;
  13542. break;
  13543. }
  13544. }
  13545. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13546. }
  13547. }
  13548. else {
  13549. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13550. arrayBuffer = new Uint16Array(indices);
  13551. }
  13552. }
  13553. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13554. this._resetIndexBufferBinding();
  13555. vbo.references = 1;
  13556. vbo.is32Bits = need32Bits;
  13557. return vbo;
  13558. };
  13559. /**
  13560. * Bind a webGL buffer to the webGL context
  13561. * @param buffer defines the buffer to bind
  13562. */
  13563. Engine.prototype.bindArrayBuffer = function (buffer) {
  13564. if (!this._vaoRecordInProgress) {
  13565. this._unbindVertexArrayObject();
  13566. }
  13567. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13568. };
  13569. /**
  13570. * Bind an uniform buffer to the current webGL context
  13571. * @param buffer defines the buffer to bind
  13572. */
  13573. Engine.prototype.bindUniformBuffer = function (buffer) {
  13574. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13575. };
  13576. /**
  13577. * Bind a buffer to the current webGL context at a given location
  13578. * @param buffer defines the buffer to bind
  13579. * @param location defines the index where to bind the buffer
  13580. */
  13581. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13582. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13583. };
  13584. /**
  13585. * Bind a specific block at a given index in a specific shader program
  13586. * @param shaderProgram defines the shader program
  13587. * @param blockName defines the block name
  13588. * @param index defines the index where to bind the block
  13589. */
  13590. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13591. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13592. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13593. };
  13594. ;
  13595. Engine.prototype.bindIndexBuffer = function (buffer) {
  13596. if (!this._vaoRecordInProgress) {
  13597. this._unbindVertexArrayObject();
  13598. }
  13599. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13600. };
  13601. Engine.prototype.bindBuffer = function (buffer, target) {
  13602. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13603. this._gl.bindBuffer(target, buffer);
  13604. this._currentBoundBuffer[target] = buffer;
  13605. }
  13606. };
  13607. /**
  13608. * update the bound buffer with the given data
  13609. * @param data defines the data to update
  13610. */
  13611. Engine.prototype.updateArrayBuffer = function (data) {
  13612. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13613. };
  13614. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13615. var pointer = this._currentBufferPointers[indx];
  13616. var changed = false;
  13617. if (!pointer.active) {
  13618. changed = true;
  13619. pointer.active = true;
  13620. pointer.index = indx;
  13621. pointer.size = size;
  13622. pointer.type = type;
  13623. pointer.normalized = normalized;
  13624. pointer.stride = stride;
  13625. pointer.offset = offset;
  13626. pointer.buffer = buffer;
  13627. }
  13628. else {
  13629. if (pointer.buffer !== buffer) {
  13630. pointer.buffer = buffer;
  13631. changed = true;
  13632. }
  13633. if (pointer.size !== size) {
  13634. pointer.size = size;
  13635. changed = true;
  13636. }
  13637. if (pointer.type !== type) {
  13638. pointer.type = type;
  13639. changed = true;
  13640. }
  13641. if (pointer.normalized !== normalized) {
  13642. pointer.normalized = normalized;
  13643. changed = true;
  13644. }
  13645. if (pointer.stride !== stride) {
  13646. pointer.stride = stride;
  13647. changed = true;
  13648. }
  13649. if (pointer.offset !== offset) {
  13650. pointer.offset = offset;
  13651. changed = true;
  13652. }
  13653. }
  13654. if (changed || this._vaoRecordInProgress) {
  13655. this.bindArrayBuffer(buffer);
  13656. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13657. }
  13658. };
  13659. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13660. if (indexBuffer == null) {
  13661. return;
  13662. }
  13663. if (this._cachedIndexBuffer !== indexBuffer) {
  13664. this._cachedIndexBuffer = indexBuffer;
  13665. this.bindIndexBuffer(indexBuffer);
  13666. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13667. }
  13668. };
  13669. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13670. var attributes = effect.getAttributesNames();
  13671. if (!this._vaoRecordInProgress) {
  13672. this._unbindVertexArrayObject();
  13673. }
  13674. this.unbindAllAttributes();
  13675. for (var index = 0; index < attributes.length; index++) {
  13676. var order = effect.getAttributeLocation(index);
  13677. if (order >= 0) {
  13678. var vertexBuffer = vertexBuffers[attributes[index]];
  13679. if (!vertexBuffer) {
  13680. continue;
  13681. }
  13682. this._gl.enableVertexAttribArray(order);
  13683. if (!this._vaoRecordInProgress) {
  13684. this._vertexAttribArraysEnabled[order] = true;
  13685. }
  13686. var buffer = vertexBuffer.getBuffer();
  13687. if (buffer) {
  13688. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13689. if (vertexBuffer.getIsInstanced()) {
  13690. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13691. if (!this._vaoRecordInProgress) {
  13692. this._currentInstanceLocations.push(order);
  13693. this._currentInstanceBuffers.push(buffer);
  13694. }
  13695. }
  13696. }
  13697. }
  13698. }
  13699. };
  13700. /**
  13701. * Records a vertex array object
  13702. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13703. * @param vertexBuffers defines the list of vertex buffers to store
  13704. * @param indexBuffer defines the index buffer to store
  13705. * @param effect defines the effect to store
  13706. * @returns the new vertex array object
  13707. */
  13708. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13709. var vao = this._gl.createVertexArray();
  13710. this._vaoRecordInProgress = true;
  13711. this._gl.bindVertexArray(vao);
  13712. this._mustWipeVertexAttributes = true;
  13713. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13714. this.bindIndexBuffer(indexBuffer);
  13715. this._vaoRecordInProgress = false;
  13716. this._gl.bindVertexArray(null);
  13717. return vao;
  13718. };
  13719. /**
  13720. * Bind a specific vertex array object
  13721. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13722. * @param vertexArrayObject defines the vertex array object to bind
  13723. * @param indexBuffer defines the index buffer to bind
  13724. */
  13725. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13726. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13727. this._cachedVertexArrayObject = vertexArrayObject;
  13728. this._gl.bindVertexArray(vertexArrayObject);
  13729. this._cachedVertexBuffers = null;
  13730. this._cachedIndexBuffer = null;
  13731. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13732. this._mustWipeVertexAttributes = true;
  13733. }
  13734. };
  13735. /**
  13736. * Bind webGl buffers directly to the webGL context
  13737. * @param vertexBuffer defines the vertex buffer to bind
  13738. * @param indexBuffer defines the index buffer to bind
  13739. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13740. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13741. * @param effect defines the effect associated with the vertex buffer
  13742. */
  13743. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13744. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13745. this._cachedVertexBuffers = vertexBuffer;
  13746. this._cachedEffectForVertexBuffers = effect;
  13747. var attributesCount = effect.getAttributesCount();
  13748. this._unbindVertexArrayObject();
  13749. this.unbindAllAttributes();
  13750. var offset = 0;
  13751. for (var index = 0; index < attributesCount; index++) {
  13752. if (index < vertexDeclaration.length) {
  13753. var order = effect.getAttributeLocation(index);
  13754. if (order >= 0) {
  13755. this._gl.enableVertexAttribArray(order);
  13756. this._vertexAttribArraysEnabled[order] = true;
  13757. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13758. }
  13759. offset += vertexDeclaration[index] * 4;
  13760. }
  13761. }
  13762. }
  13763. this._bindIndexBufferWithCache(indexBuffer);
  13764. };
  13765. Engine.prototype._unbindVertexArrayObject = function () {
  13766. if (!this._cachedVertexArrayObject) {
  13767. return;
  13768. }
  13769. this._cachedVertexArrayObject = null;
  13770. this._gl.bindVertexArray(null);
  13771. };
  13772. /**
  13773. * Bind a list of vertex buffers to the webGL context
  13774. * @param vertexBuffers defines the list of vertex buffers to bind
  13775. * @param indexBuffer defines the index buffer to bind
  13776. * @param effect defines the effect associated with the vertex buffers
  13777. */
  13778. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13779. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13780. this._cachedVertexBuffers = vertexBuffers;
  13781. this._cachedEffectForVertexBuffers = effect;
  13782. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13783. }
  13784. this._bindIndexBufferWithCache(indexBuffer);
  13785. };
  13786. /**
  13787. * Unbind all instance attributes
  13788. */
  13789. Engine.prototype.unbindInstanceAttributes = function () {
  13790. var boundBuffer;
  13791. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13792. var instancesBuffer = this._currentInstanceBuffers[i];
  13793. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13794. boundBuffer = instancesBuffer;
  13795. this.bindArrayBuffer(instancesBuffer);
  13796. }
  13797. var offsetLocation = this._currentInstanceLocations[i];
  13798. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13799. }
  13800. this._currentInstanceBuffers.length = 0;
  13801. this._currentInstanceLocations.length = 0;
  13802. };
  13803. /**
  13804. * Release and free the memory of a vertex array object
  13805. * @param vao defines the vertex array object to delete
  13806. */
  13807. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13808. this._gl.deleteVertexArray(vao);
  13809. };
  13810. /** @hidden */
  13811. Engine.prototype._releaseBuffer = function (buffer) {
  13812. buffer.references--;
  13813. if (buffer.references === 0) {
  13814. this._gl.deleteBuffer(buffer);
  13815. return true;
  13816. }
  13817. return false;
  13818. };
  13819. /**
  13820. * Creates a webGL buffer to use with instanciation
  13821. * @param capacity defines the size of the buffer
  13822. * @returns the webGL buffer
  13823. */
  13824. Engine.prototype.createInstancesBuffer = function (capacity) {
  13825. var buffer = this._gl.createBuffer();
  13826. if (!buffer) {
  13827. throw new Error("Unable to create instance buffer");
  13828. }
  13829. buffer.capacity = capacity;
  13830. this.bindArrayBuffer(buffer);
  13831. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13832. return buffer;
  13833. };
  13834. /**
  13835. * Delete a webGL buffer used with instanciation
  13836. * @param buffer defines the webGL buffer to delete
  13837. */
  13838. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13839. this._gl.deleteBuffer(buffer);
  13840. };
  13841. /**
  13842. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13843. * @param instancesBuffer defines the webGL buffer to update and bind
  13844. * @param data defines the data to store in the buffer
  13845. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13846. */
  13847. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13848. this.bindArrayBuffer(instancesBuffer);
  13849. if (data) {
  13850. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13851. }
  13852. if (offsetLocations[0].index !== undefined) {
  13853. var stride = 0;
  13854. for (var i = 0; i < offsetLocations.length; i++) {
  13855. var ai = offsetLocations[i];
  13856. stride += ai.attributeSize * 4;
  13857. }
  13858. for (var i = 0; i < offsetLocations.length; i++) {
  13859. var ai = offsetLocations[i];
  13860. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13861. this._gl.enableVertexAttribArray(ai.index);
  13862. this._vertexAttribArraysEnabled[ai.index] = true;
  13863. }
  13864. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13865. this._gl.vertexAttribDivisor(ai.index, 1);
  13866. this._currentInstanceLocations.push(ai.index);
  13867. this._currentInstanceBuffers.push(instancesBuffer);
  13868. }
  13869. }
  13870. else {
  13871. for (var index = 0; index < 4; index++) {
  13872. var offsetLocation = offsetLocations[index];
  13873. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13874. this._gl.enableVertexAttribArray(offsetLocation);
  13875. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13876. }
  13877. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13878. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13879. this._currentInstanceLocations.push(offsetLocation);
  13880. this._currentInstanceBuffers.push(instancesBuffer);
  13881. }
  13882. }
  13883. };
  13884. /**
  13885. * Apply all cached states (depth, culling, stencil and alpha)
  13886. */
  13887. Engine.prototype.applyStates = function () {
  13888. this._depthCullingState.apply(this._gl);
  13889. this._stencilState.apply(this._gl);
  13890. this._alphaState.apply(this._gl);
  13891. };
  13892. /**
  13893. * Send a draw order
  13894. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13895. * @param indexStart defines the starting index
  13896. * @param indexCount defines the number of index to draw
  13897. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13898. */
  13899. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13900. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13901. };
  13902. /**
  13903. * Draw a list of points
  13904. * @param verticesStart defines the index of first vertex to draw
  13905. * @param verticesCount defines the count of vertices to draw
  13906. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13907. */
  13908. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13909. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13910. };
  13911. /**
  13912. * Draw a list of unindexed primitives
  13913. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13914. * @param verticesStart defines the index of first vertex to draw
  13915. * @param verticesCount defines the count of vertices to draw
  13916. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13917. */
  13918. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13919. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13920. };
  13921. /**
  13922. * Draw a list of indexed primitives
  13923. * @param fillMode defines the primitive to use
  13924. * @param indexStart defines the starting index
  13925. * @param indexCount defines the number of index to draw
  13926. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13927. */
  13928. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13929. // Apply states
  13930. this.applyStates();
  13931. this._drawCalls.addCount(1, false);
  13932. // Render
  13933. var drawMode = this._drawMode(fillMode);
  13934. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13935. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13936. if (instancesCount) {
  13937. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13938. }
  13939. else {
  13940. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13941. }
  13942. };
  13943. /**
  13944. * Draw a list of unindexed primitives
  13945. * @param fillMode defines the primitive to use
  13946. * @param verticesStart defines the index of first vertex to draw
  13947. * @param verticesCount defines the count of vertices to draw
  13948. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13949. */
  13950. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13951. // Apply states
  13952. this.applyStates();
  13953. this._drawCalls.addCount(1, false);
  13954. var drawMode = this._drawMode(fillMode);
  13955. if (instancesCount) {
  13956. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13957. }
  13958. else {
  13959. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13960. }
  13961. };
  13962. Engine.prototype._drawMode = function (fillMode) {
  13963. switch (fillMode) {
  13964. // Triangle views
  13965. case BABYLON.Material.TriangleFillMode:
  13966. return this._gl.TRIANGLES;
  13967. case BABYLON.Material.PointFillMode:
  13968. return this._gl.POINTS;
  13969. case BABYLON.Material.WireFrameFillMode:
  13970. return this._gl.LINES;
  13971. // Draw modes
  13972. case BABYLON.Material.PointListDrawMode:
  13973. return this._gl.POINTS;
  13974. case BABYLON.Material.LineListDrawMode:
  13975. return this._gl.LINES;
  13976. case BABYLON.Material.LineLoopDrawMode:
  13977. return this._gl.LINE_LOOP;
  13978. case BABYLON.Material.LineStripDrawMode:
  13979. return this._gl.LINE_STRIP;
  13980. case BABYLON.Material.TriangleStripDrawMode:
  13981. return this._gl.TRIANGLE_STRIP;
  13982. case BABYLON.Material.TriangleFanDrawMode:
  13983. return this._gl.TRIANGLE_FAN;
  13984. default:
  13985. return this._gl.TRIANGLES;
  13986. }
  13987. };
  13988. // Shaders
  13989. /** @hidden */
  13990. Engine.prototype._releaseEffect = function (effect) {
  13991. if (this._compiledEffects[effect._key]) {
  13992. delete this._compiledEffects[effect._key];
  13993. this._deleteProgram(effect.getProgram());
  13994. }
  13995. };
  13996. /** @hidden */
  13997. Engine.prototype._deleteProgram = function (program) {
  13998. if (program) {
  13999. program.__SPECTOR_rebuildProgram = null;
  14000. if (program.transformFeedback) {
  14001. this.deleteTransformFeedback(program.transformFeedback);
  14002. program.transformFeedback = null;
  14003. }
  14004. this._gl.deleteProgram(program);
  14005. }
  14006. };
  14007. /**
  14008. * Create a new effect (used to store vertex/fragment shaders)
  14009. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14010. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14011. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14012. * @param samplers defines an array of string used to represent textures
  14013. * @param defines defines the string containing the defines to use to compile the shaders
  14014. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14015. * @param onCompiled defines a function to call when the effect creation is successful
  14016. * @param onError defines a function to call when the effect creation has failed
  14017. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14018. * @returns the new Effect
  14019. */
  14020. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14021. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14022. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14023. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14024. if (this._compiledEffects[name]) {
  14025. var compiledEffect = this._compiledEffects[name];
  14026. if (onCompiled && compiledEffect.isReady()) {
  14027. onCompiled(compiledEffect);
  14028. }
  14029. return compiledEffect;
  14030. }
  14031. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14032. effect._key = name;
  14033. this._compiledEffects[name] = effect;
  14034. return effect;
  14035. };
  14036. /**
  14037. * Create an effect to use with particle systems.
  14038. * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration
  14039. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14040. * @param uniformsNames defines a list of attribute names
  14041. * @param samplers defines an array of string used to represent textures
  14042. * @param defines defines the string containing the defines to use to compile the shaders
  14043. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14044. * @param onCompiled defines a function to call when the effect creation is successful
  14045. * @param onError defines a function to call when the effect creation has failed
  14046. * @returns the new Effect
  14047. */
  14048. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14049. if (uniformsNames === void 0) { uniformsNames = []; }
  14050. if (samplers === void 0) { samplers = []; }
  14051. if (defines === void 0) { defines = ""; }
  14052. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  14053. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  14054. if (defines.indexOf(" BILLBOARD") === -1) {
  14055. defines += "\n#define BILLBOARD\n";
  14056. }
  14057. if (samplers.indexOf("diffuseSampler") === -1) {
  14058. samplers.push("diffuseSampler");
  14059. }
  14060. return this.createEffect({
  14061. vertex: "particles",
  14062. fragmentElement: fragmentName
  14063. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  14064. };
  14065. /**
  14066. * Directly creates a webGL program
  14067. * @param vertexCode defines the vertex shader code to use
  14068. * @param fragmentCode defines the fragment shader code to use
  14069. * @param context defines the webGL context to use (if not set, the current one will be used)
  14070. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14071. * @returns the new webGL program
  14072. */
  14073. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14074. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14075. context = context || this._gl;
  14076. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14077. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14078. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14079. };
  14080. /**
  14081. * Creates a webGL program
  14082. * @param vertexCode defines the vertex shader code to use
  14083. * @param fragmentCode defines the fragment shader code to use
  14084. * @param defines defines the string containing the defines to use to compile the shaders
  14085. * @param context defines the webGL context to use (if not set, the current one will be used)
  14086. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14087. * @returns the new webGL program
  14088. */
  14089. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14090. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14091. context = context || this._gl;
  14092. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14093. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14094. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14095. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14096. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14097. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14098. return program;
  14099. };
  14100. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14101. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14102. var shaderProgram = context.createProgram();
  14103. if (!shaderProgram) {
  14104. throw new Error("Unable to create program");
  14105. }
  14106. context.attachShader(shaderProgram, vertexShader);
  14107. context.attachShader(shaderProgram, fragmentShader);
  14108. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14109. var transformFeedback = this.createTransformFeedback();
  14110. this.bindTransformFeedback(transformFeedback);
  14111. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14112. shaderProgram.transformFeedback = transformFeedback;
  14113. }
  14114. context.linkProgram(shaderProgram);
  14115. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14116. this.bindTransformFeedback(null);
  14117. }
  14118. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14119. if (!linked) {
  14120. var error = context.getProgramInfoLog(shaderProgram);
  14121. if (error) {
  14122. throw new Error(error);
  14123. }
  14124. }
  14125. context.validateProgram(shaderProgram);
  14126. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14127. if (!validated) {
  14128. var error = context.getProgramInfoLog(shaderProgram);
  14129. if (error) {
  14130. throw new Error(error);
  14131. }
  14132. }
  14133. context.deleteShader(vertexShader);
  14134. context.deleteShader(fragmentShader);
  14135. return shaderProgram;
  14136. };
  14137. /**
  14138. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14139. * @param shaderProgram defines the webGL program to use
  14140. * @param uniformsNames defines the list of uniform names
  14141. * @returns an array of webGL uniform locations
  14142. */
  14143. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14144. var results = new Array();
  14145. for (var index = 0; index < uniformsNames.length; index++) {
  14146. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14147. }
  14148. return results;
  14149. };
  14150. /**
  14151. * Gets the lsit of active attributes for a given webGL program
  14152. * @param shaderProgram defines the webGL program to use
  14153. * @param attributesNames defines the list of attribute names to get
  14154. * @returns an array of indices indicating the offset of each attribute
  14155. */
  14156. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14157. var results = [];
  14158. for (var index = 0; index < attributesNames.length; index++) {
  14159. try {
  14160. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14161. }
  14162. catch (e) {
  14163. results.push(-1);
  14164. }
  14165. }
  14166. return results;
  14167. };
  14168. /**
  14169. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14170. * @param effect defines the effect to activate
  14171. */
  14172. Engine.prototype.enableEffect = function (effect) {
  14173. if (!effect) {
  14174. return;
  14175. }
  14176. // Use program
  14177. this.bindSamplers(effect);
  14178. this._currentEffect = effect;
  14179. if (effect.onBind) {
  14180. effect.onBind(effect);
  14181. }
  14182. effect.onBindObservable.notifyObservers(effect);
  14183. };
  14184. /**
  14185. * Set the value of an uniform to an array of int32
  14186. * @param uniform defines the webGL uniform location where to store the value
  14187. * @param array defines the array of int32 to store
  14188. */
  14189. Engine.prototype.setIntArray = function (uniform, array) {
  14190. if (!uniform)
  14191. return;
  14192. this._gl.uniform1iv(uniform, array);
  14193. };
  14194. /**
  14195. * Set the value of an uniform to an array of int32 (stored as vec2)
  14196. * @param uniform defines the webGL uniform location where to store the value
  14197. * @param array defines the array of int32 to store
  14198. */
  14199. Engine.prototype.setIntArray2 = function (uniform, array) {
  14200. if (!uniform || array.length % 2 !== 0)
  14201. return;
  14202. this._gl.uniform2iv(uniform, array);
  14203. };
  14204. /**
  14205. * Set the value of an uniform to an array of int32 (stored as vec3)
  14206. * @param uniform defines the webGL uniform location where to store the value
  14207. * @param array defines the array of int32 to store
  14208. */
  14209. Engine.prototype.setIntArray3 = function (uniform, array) {
  14210. if (!uniform || array.length % 3 !== 0)
  14211. return;
  14212. this._gl.uniform3iv(uniform, array);
  14213. };
  14214. /**
  14215. * Set the value of an uniform to an array of int32 (stored as vec4)
  14216. * @param uniform defines the webGL uniform location where to store the value
  14217. * @param array defines the array of int32 to store
  14218. */
  14219. Engine.prototype.setIntArray4 = function (uniform, array) {
  14220. if (!uniform || array.length % 4 !== 0)
  14221. return;
  14222. this._gl.uniform4iv(uniform, array);
  14223. };
  14224. /**
  14225. * Set the value of an uniform to an array of float32
  14226. * @param uniform defines the webGL uniform location where to store the value
  14227. * @param array defines the array of float32 to store
  14228. */
  14229. Engine.prototype.setFloatArray = function (uniform, array) {
  14230. if (!uniform)
  14231. return;
  14232. this._gl.uniform1fv(uniform, array);
  14233. };
  14234. /**
  14235. * Set the value of an uniform to an array of float32 (stored as vec2)
  14236. * @param uniform defines the webGL uniform location where to store the value
  14237. * @param array defines the array of float32 to store
  14238. */
  14239. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14240. if (!uniform || array.length % 2 !== 0)
  14241. return;
  14242. this._gl.uniform2fv(uniform, array);
  14243. };
  14244. /**
  14245. * Set the value of an uniform to an array of float32 (stored as vec3)
  14246. * @param uniform defines the webGL uniform location where to store the value
  14247. * @param array defines the array of float32 to store
  14248. */
  14249. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14250. if (!uniform || array.length % 3 !== 0)
  14251. return;
  14252. this._gl.uniform3fv(uniform, array);
  14253. };
  14254. /**
  14255. * Set the value of an uniform to an array of float32 (stored as vec4)
  14256. * @param uniform defines the webGL uniform location where to store the value
  14257. * @param array defines the array of float32 to store
  14258. */
  14259. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14260. if (!uniform || array.length % 4 !== 0)
  14261. return;
  14262. this._gl.uniform4fv(uniform, array);
  14263. };
  14264. /**
  14265. * Set the value of an uniform to an array of number
  14266. * @param uniform defines the webGL uniform location where to store the value
  14267. * @param array defines the array of number to store
  14268. */
  14269. Engine.prototype.setArray = function (uniform, array) {
  14270. if (!uniform)
  14271. return;
  14272. this._gl.uniform1fv(uniform, array);
  14273. };
  14274. /**
  14275. * Set the value of an uniform to an array of number (stored as vec2)
  14276. * @param uniform defines the webGL uniform location where to store the value
  14277. * @param array defines the array of number to store
  14278. */
  14279. Engine.prototype.setArray2 = function (uniform, array) {
  14280. if (!uniform || array.length % 2 !== 0)
  14281. return;
  14282. this._gl.uniform2fv(uniform, array);
  14283. };
  14284. /**
  14285. * Set the value of an uniform to an array of number (stored as vec3)
  14286. * @param uniform defines the webGL uniform location where to store the value
  14287. * @param array defines the array of number to store
  14288. */
  14289. Engine.prototype.setArray3 = function (uniform, array) {
  14290. if (!uniform || array.length % 3 !== 0)
  14291. return;
  14292. this._gl.uniform3fv(uniform, array);
  14293. };
  14294. /**
  14295. * Set the value of an uniform to an array of number (stored as vec4)
  14296. * @param uniform defines the webGL uniform location where to store the value
  14297. * @param array defines the array of number to store
  14298. */
  14299. Engine.prototype.setArray4 = function (uniform, array) {
  14300. if (!uniform || array.length % 4 !== 0)
  14301. return;
  14302. this._gl.uniform4fv(uniform, array);
  14303. };
  14304. /**
  14305. * Set the value of an uniform to an array of float32 (stored as matrices)
  14306. * @param uniform defines the webGL uniform location where to store the value
  14307. * @param matrices defines the array of float32 to store
  14308. */
  14309. Engine.prototype.setMatrices = function (uniform, matrices) {
  14310. if (!uniform)
  14311. return;
  14312. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14313. };
  14314. /**
  14315. * Set the value of an uniform to a matrix
  14316. * @param uniform defines the webGL uniform location where to store the value
  14317. * @param matrix defines the matrix to store
  14318. */
  14319. Engine.prototype.setMatrix = function (uniform, matrix) {
  14320. if (!uniform)
  14321. return;
  14322. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14323. };
  14324. /**
  14325. * Set the value of an uniform to a matrix (3x3)
  14326. * @param uniform defines the webGL uniform location where to store the value
  14327. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14328. */
  14329. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14330. if (!uniform)
  14331. return;
  14332. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14333. };
  14334. /**
  14335. * Set the value of an uniform to a matrix (2x2)
  14336. * @param uniform defines the webGL uniform location where to store the value
  14337. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14338. */
  14339. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14340. if (!uniform)
  14341. return;
  14342. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14343. };
  14344. /**
  14345. * Set the value of an uniform to a number (int)
  14346. * @param uniform defines the webGL uniform location where to store the value
  14347. * @param value defines the int number to store
  14348. */
  14349. Engine.prototype.setInt = function (uniform, value) {
  14350. if (!uniform)
  14351. return;
  14352. this._gl.uniform1i(uniform, value);
  14353. };
  14354. /**
  14355. * Set the value of an uniform to a number (float)
  14356. * @param uniform defines the webGL uniform location where to store the value
  14357. * @param value defines the float number to store
  14358. */
  14359. Engine.prototype.setFloat = function (uniform, value) {
  14360. if (!uniform)
  14361. return;
  14362. this._gl.uniform1f(uniform, value);
  14363. };
  14364. /**
  14365. * Set the value of an uniform to a vec2
  14366. * @param uniform defines the webGL uniform location where to store the value
  14367. * @param x defines the 1st component of the value
  14368. * @param y defines the 2nd component of the value
  14369. */
  14370. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14371. if (!uniform)
  14372. return;
  14373. this._gl.uniform2f(uniform, x, y);
  14374. };
  14375. /**
  14376. * Set the value of an uniform to a vec3
  14377. * @param uniform defines the webGL uniform location where to store the value
  14378. * @param x defines the 1st component of the value
  14379. * @param y defines the 2nd component of the value
  14380. * @param z defines the 3rd component of the value
  14381. */
  14382. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14383. if (!uniform)
  14384. return;
  14385. this._gl.uniform3f(uniform, x, y, z);
  14386. };
  14387. /**
  14388. * Set the value of an uniform to a boolean
  14389. * @param uniform defines the webGL uniform location where to store the value
  14390. * @param bool defines the boolean to store
  14391. */
  14392. Engine.prototype.setBool = function (uniform, bool) {
  14393. if (!uniform)
  14394. return;
  14395. this._gl.uniform1i(uniform, bool);
  14396. };
  14397. /**
  14398. * Set the value of an uniform to a vec4
  14399. * @param uniform defines the webGL uniform location where to store the value
  14400. * @param x defines the 1st component of the value
  14401. * @param y defines the 2nd component of the value
  14402. * @param z defines the 3rd component of the value
  14403. * @param w defines the 4th component of the value
  14404. */
  14405. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14406. if (!uniform)
  14407. return;
  14408. this._gl.uniform4f(uniform, x, y, z, w);
  14409. };
  14410. /**
  14411. * Set the value of an uniform to a Color3
  14412. * @param uniform defines the webGL uniform location where to store the value
  14413. * @param color3 defines the color to store
  14414. */
  14415. Engine.prototype.setColor3 = function (uniform, color3) {
  14416. if (!uniform)
  14417. return;
  14418. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14419. };
  14420. /**
  14421. * Set the value of an uniform to a Color3 and an alpha value
  14422. * @param uniform defines the webGL uniform location where to store the value
  14423. * @param color3 defines the color to store
  14424. * @param alpha defines the alpha component to store
  14425. */
  14426. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14427. if (!uniform)
  14428. return;
  14429. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14430. };
  14431. /**
  14432. * Sets a Color4 on a uniform variable
  14433. * @param uniform defines the uniform location
  14434. * @param color4 defines the value to be set
  14435. */
  14436. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14437. if (!uniform)
  14438. return;
  14439. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14440. };
  14441. // States
  14442. /**
  14443. * Set various states to the webGL context
  14444. * @param culling defines backface culling state
  14445. * @param zOffset defines the value to apply to zOffset (0 by default)
  14446. * @param force defines if states must be applied even if cache is up to date
  14447. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14448. */
  14449. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14450. if (zOffset === void 0) { zOffset = 0; }
  14451. if (reverseSide === void 0) { reverseSide = false; }
  14452. // Culling
  14453. if (this._depthCullingState.cull !== culling || force) {
  14454. this._depthCullingState.cull = culling;
  14455. }
  14456. // Cull face
  14457. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14458. if (this._depthCullingState.cullFace !== cullFace || force) {
  14459. this._depthCullingState.cullFace = cullFace;
  14460. }
  14461. // Z offset
  14462. this.setZOffset(zOffset);
  14463. // Front face
  14464. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14465. if (this._depthCullingState.frontFace !== frontFace || force) {
  14466. this._depthCullingState.frontFace = frontFace;
  14467. }
  14468. };
  14469. /**
  14470. * Set the z offset to apply to current rendering
  14471. * @param value defines the offset to apply
  14472. */
  14473. Engine.prototype.setZOffset = function (value) {
  14474. this._depthCullingState.zOffset = value;
  14475. };
  14476. /**
  14477. * Gets the current value of the zOffset
  14478. * @returns the current zOffset state
  14479. */
  14480. Engine.prototype.getZOffset = function () {
  14481. return this._depthCullingState.zOffset;
  14482. };
  14483. /**
  14484. * Enable or disable depth buffering
  14485. * @param enable defines the state to set
  14486. */
  14487. Engine.prototype.setDepthBuffer = function (enable) {
  14488. this._depthCullingState.depthTest = enable;
  14489. };
  14490. /**
  14491. * Gets a boolean indicating if depth writing is enabled
  14492. * @returns the current depth writing state
  14493. */
  14494. Engine.prototype.getDepthWrite = function () {
  14495. return this._depthCullingState.depthMask;
  14496. };
  14497. /**
  14498. * Enable or disable depth writing
  14499. * @param enable defines the state to set
  14500. */
  14501. Engine.prototype.setDepthWrite = function (enable) {
  14502. this._depthCullingState.depthMask = enable;
  14503. };
  14504. /**
  14505. * Enable or disable color writing
  14506. * @param enable defines the state to set
  14507. */
  14508. Engine.prototype.setColorWrite = function (enable) {
  14509. this._gl.colorMask(enable, enable, enable, enable);
  14510. this._colorWrite = enable;
  14511. };
  14512. /**
  14513. * Gets a boolean indicating if color writing is enabled
  14514. * @returns the current color writing state
  14515. */
  14516. Engine.prototype.getColorWrite = function () {
  14517. return this._colorWrite;
  14518. };
  14519. /**
  14520. * Sets alpha constants used by some alpha blending modes
  14521. * @param r defines the red component
  14522. * @param g defines the green component
  14523. * @param b defines the blue component
  14524. * @param a defines the alpha component
  14525. */
  14526. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14527. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14528. };
  14529. /**
  14530. * Sets the current alpha mode
  14531. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14532. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14533. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14534. */
  14535. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14536. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14537. if (this._alphaMode === mode) {
  14538. return;
  14539. }
  14540. switch (mode) {
  14541. case Engine.ALPHA_DISABLE:
  14542. this._alphaState.alphaBlend = false;
  14543. break;
  14544. case Engine.ALPHA_PREMULTIPLIED:
  14545. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14546. this._alphaState.alphaBlend = true;
  14547. break;
  14548. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14549. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14550. this._alphaState.alphaBlend = true;
  14551. break;
  14552. case Engine.ALPHA_COMBINE:
  14553. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14554. this._alphaState.alphaBlend = true;
  14555. break;
  14556. case Engine.ALPHA_ONEONE:
  14557. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14558. this._alphaState.alphaBlend = true;
  14559. break;
  14560. case Engine.ALPHA_ADD:
  14561. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14562. this._alphaState.alphaBlend = true;
  14563. break;
  14564. case Engine.ALPHA_SUBTRACT:
  14565. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14566. this._alphaState.alphaBlend = true;
  14567. break;
  14568. case Engine.ALPHA_MULTIPLY:
  14569. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14570. this._alphaState.alphaBlend = true;
  14571. break;
  14572. case Engine.ALPHA_MAXIMIZED:
  14573. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14574. this._alphaState.alphaBlend = true;
  14575. break;
  14576. case Engine.ALPHA_INTERPOLATE:
  14577. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14578. this._alphaState.alphaBlend = true;
  14579. break;
  14580. case Engine.ALPHA_SCREENMODE:
  14581. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14582. this._alphaState.alphaBlend = true;
  14583. break;
  14584. }
  14585. if (!noDepthWriteChange) {
  14586. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14587. }
  14588. this._alphaMode = mode;
  14589. };
  14590. /**
  14591. * Gets the current alpha mode
  14592. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14593. * @returns the current alpha mode
  14594. */
  14595. Engine.prototype.getAlphaMode = function () {
  14596. return this._alphaMode;
  14597. };
  14598. // Textures
  14599. /**
  14600. * Clears the list of texture accessible through engine.
  14601. * This can help preventing texture load conflict due to name collision.
  14602. */
  14603. Engine.prototype.clearInternalTexturesCache = function () {
  14604. this._internalTexturesCache = [];
  14605. };
  14606. /**
  14607. * Force the entire cache to be cleared
  14608. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14609. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14610. */
  14611. Engine.prototype.wipeCaches = function (bruteForce) {
  14612. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14613. return;
  14614. }
  14615. this._currentEffect = null;
  14616. this._unpackFlipYCached = null;
  14617. this._viewportCached.x = 0;
  14618. this._viewportCached.y = 0;
  14619. this._viewportCached.z = 0;
  14620. this._viewportCached.w = 0;
  14621. if (bruteForce) {
  14622. this.resetTextureCache();
  14623. this._currentProgram = null;
  14624. this._stencilState.reset();
  14625. this._depthCullingState.reset();
  14626. this.setDepthFunctionToLessOrEqual();
  14627. this._alphaState.reset();
  14628. }
  14629. this._resetVertexBufferBinding();
  14630. this._cachedIndexBuffer = null;
  14631. this._cachedEffectForVertexBuffers = null;
  14632. this._unbindVertexArrayObject();
  14633. this.bindIndexBuffer(null);
  14634. };
  14635. /**
  14636. * Set the compressed texture format to use, based on the formats you have, and the formats
  14637. * supported by the hardware / browser.
  14638. *
  14639. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14640. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14641. * to API arguments needed to compressed textures. This puts the burden on the container
  14642. * generator to house the arcane code for determining these for current & future formats.
  14643. *
  14644. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14645. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14646. *
  14647. * Note: The result of this call is not taken into account when a texture is base64.
  14648. *
  14649. * @param formatsAvailable defines the list of those format families you have created
  14650. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14651. *
  14652. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14653. * @returns The extension selected.
  14654. */
  14655. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14656. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14657. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14658. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14659. return this._textureFormatInUse = this._texturesSupported[i];
  14660. }
  14661. }
  14662. }
  14663. // actively set format to nothing, to allow this to be called more than once
  14664. // and possibly fail the 2nd time
  14665. this._textureFormatInUse = null;
  14666. return null;
  14667. };
  14668. /** @hidden */
  14669. Engine.prototype._createTexture = function () {
  14670. var texture = this._gl.createTexture();
  14671. if (!texture) {
  14672. throw new Error("Unable to create texture");
  14673. }
  14674. return texture;
  14675. };
  14676. /**
  14677. * Usually called from BABYLON.Texture.ts.
  14678. * Passed information to create a WebGLTexture
  14679. * @param urlArg defines a value which contains one of the following:
  14680. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14681. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14682. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14683. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14684. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14685. * @param scene needed for loading to the correct scene
  14686. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14687. * @param onLoad optional callback to be called upon successful completion
  14688. * @param onError optional callback to be called upon failure
  14689. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14690. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14691. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14692. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14693. */
  14694. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14695. var _this = this;
  14696. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14697. if (onLoad === void 0) { onLoad = null; }
  14698. if (onError === void 0) { onError = null; }
  14699. if (buffer === void 0) { buffer = null; }
  14700. if (fallback === void 0) { fallback = null; }
  14701. if (format === void 0) { format = null; }
  14702. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14703. var fromData = url.substr(0, 5) === "data:";
  14704. var fromBlob = url.substr(0, 5) === "blob:";
  14705. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14706. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14707. // establish the file extension, if possible
  14708. var lastDot = url.lastIndexOf('.');
  14709. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14710. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14711. var isTGA = (extension.indexOf(".tga") === 0);
  14712. // determine if a ktx file should be substituted
  14713. var isKTX = false;
  14714. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14715. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14716. isKTX = true;
  14717. }
  14718. if (scene) {
  14719. scene._addPendingData(texture);
  14720. }
  14721. texture.url = url;
  14722. texture.generateMipMaps = !noMipmap;
  14723. texture.samplingMode = samplingMode;
  14724. texture.invertY = invertY;
  14725. if (!this._doNotHandleContextLost) {
  14726. // Keep a link to the buffer only if we plan to handle context lost
  14727. texture._buffer = buffer;
  14728. }
  14729. var onLoadObserver = null;
  14730. if (onLoad && !fallback) {
  14731. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14732. }
  14733. if (!fallback)
  14734. this._internalTexturesCache.push(texture);
  14735. var onerror = function (message, exception) {
  14736. if (scene) {
  14737. scene._removePendingData(texture);
  14738. }
  14739. if (onLoadObserver && !isKTX) {
  14740. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14741. texture.onLoadedObservable.remove(onLoadObserver);
  14742. }
  14743. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14744. if (isKTX) {
  14745. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14746. }
  14747. else if (BABYLON.Tools.UseFallbackTexture) {
  14748. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14749. }
  14750. if (onError) {
  14751. onError(message || "Unknown error", exception);
  14752. }
  14753. };
  14754. var callback = null;
  14755. // processing for non-image formats
  14756. if (isKTX || isTGA || isDDS) {
  14757. if (isKTX) {
  14758. callback = function (data) {
  14759. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14760. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14761. ktx.uploadLevels(_this._gl, !noMipmap);
  14762. return false;
  14763. }, samplingMode);
  14764. };
  14765. }
  14766. else if (isTGA) {
  14767. callback = function (arrayBuffer) {
  14768. var data = new Uint8Array(arrayBuffer);
  14769. var header = BABYLON.TGATools.GetTGAHeader(data);
  14770. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14771. BABYLON.TGATools.UploadContent(_this._gl, data);
  14772. return false;
  14773. }, samplingMode);
  14774. };
  14775. }
  14776. else if (isDDS) {
  14777. callback = function (data) {
  14778. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14779. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14780. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14781. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14782. return false;
  14783. }, samplingMode);
  14784. };
  14785. }
  14786. if (!buffer) {
  14787. this._loadFile(url, function (data) {
  14788. if (callback) {
  14789. callback(data);
  14790. }
  14791. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14792. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14793. });
  14794. }
  14795. else {
  14796. if (callback) {
  14797. callback(buffer);
  14798. }
  14799. }
  14800. // image format processing
  14801. }
  14802. else {
  14803. var onload = function (img) {
  14804. if (fromBlob && !_this._doNotHandleContextLost) {
  14805. // We need to store the image if we need to rebuild the texture
  14806. // in case of a webgl context lost
  14807. texture._buffer = img;
  14808. }
  14809. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14810. var gl = _this._gl;
  14811. var isPot = (img.width === potWidth && img.height === potHeight);
  14812. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14813. if (isPot) {
  14814. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14815. return false;
  14816. }
  14817. var maxTextureSize = _this._caps.maxTextureSize;
  14818. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14819. _this._prepareWorkingCanvas();
  14820. if (!_this._workingCanvas || !_this._workingContext) {
  14821. return false;
  14822. }
  14823. _this._workingCanvas.width = potWidth;
  14824. _this._workingCanvas.height = potHeight;
  14825. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14826. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14827. texture.width = potWidth;
  14828. texture.height = potHeight;
  14829. return false;
  14830. }
  14831. else {
  14832. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14833. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14834. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14835. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14836. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14837. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14838. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14839. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14840. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14841. _this._releaseTexture(source_1);
  14842. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14843. continuationCallback();
  14844. });
  14845. }
  14846. return true;
  14847. }, samplingMode);
  14848. };
  14849. if (!fromData || isBase64) {
  14850. if (buffer instanceof HTMLImageElement) {
  14851. onload(buffer);
  14852. }
  14853. else {
  14854. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14855. }
  14856. }
  14857. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14858. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14859. }
  14860. else {
  14861. onload(buffer);
  14862. }
  14863. }
  14864. return texture;
  14865. };
  14866. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14867. var _this = this;
  14868. var rtt = this.createRenderTargetTexture({
  14869. width: destination.width,
  14870. height: destination.height,
  14871. }, {
  14872. generateMipMaps: false,
  14873. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14874. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14875. generateDepthBuffer: false,
  14876. generateStencilBuffer: false
  14877. });
  14878. if (!this._rescalePostProcess) {
  14879. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14880. }
  14881. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14882. _this._rescalePostProcess.onApply = function (effect) {
  14883. effect._bindTexture("textureSampler", source);
  14884. };
  14885. var hostingScene = scene;
  14886. if (!hostingScene) {
  14887. hostingScene = _this.scenes[_this.scenes.length - 1];
  14888. }
  14889. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14890. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14891. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14892. _this.unBindFramebuffer(rtt);
  14893. _this._releaseTexture(rtt);
  14894. if (onComplete) {
  14895. onComplete();
  14896. }
  14897. });
  14898. };
  14899. /**
  14900. * Update a raw texture
  14901. * @param texture defines the texture to update
  14902. * @param data defines the data to store in the texture
  14903. * @param format defines the format of the data
  14904. * @param invertY defines if data must be stored with Y axis inverted
  14905. * @param compression defines the compression used (null by default)
  14906. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14907. */
  14908. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14909. if (compression === void 0) { compression = null; }
  14910. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14911. if (!texture) {
  14912. return;
  14913. }
  14914. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14915. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14916. // babylon's internalFormat but gl's texImage2D format
  14917. var internalFormat = this._getInternalFormat(format);
  14918. var textureType = this._getWebGLTextureType(type);
  14919. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14920. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14921. if (!this._doNotHandleContextLost) {
  14922. texture._bufferView = data;
  14923. texture.format = format;
  14924. texture.type = type;
  14925. texture.invertY = invertY;
  14926. texture._compression = compression;
  14927. }
  14928. if (texture.width % 4 !== 0) {
  14929. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14930. }
  14931. if (compression && data) {
  14932. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14933. }
  14934. else {
  14935. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14936. }
  14937. if (texture.generateMipMaps) {
  14938. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14939. }
  14940. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14941. // this.resetTextureCache();
  14942. texture.isReady = true;
  14943. };
  14944. /**
  14945. * Creates a raw texture
  14946. * @param data defines the data to store in the texture
  14947. * @param width defines the width of the texture
  14948. * @param height defines the height of the texture
  14949. * @param format defines the format of the data
  14950. * @param generateMipMaps defines if the engine should generate the mip levels
  14951. * @param invertY defines if data must be stored with Y axis inverted
  14952. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14953. * @param compression defines the compression used (null by default)
  14954. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14955. * @returns the raw texture inside an InternalTexture
  14956. */
  14957. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14958. if (compression === void 0) { compression = null; }
  14959. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14960. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14961. texture.baseWidth = width;
  14962. texture.baseHeight = height;
  14963. texture.width = width;
  14964. texture.height = height;
  14965. texture.format = format;
  14966. texture.generateMipMaps = generateMipMaps;
  14967. texture.samplingMode = samplingMode;
  14968. texture.invertY = invertY;
  14969. texture._compression = compression;
  14970. texture.type = type;
  14971. if (!this._doNotHandleContextLost) {
  14972. texture._bufferView = data;
  14973. }
  14974. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14975. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14976. // Filters
  14977. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14978. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14979. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14980. if (generateMipMaps) {
  14981. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14982. }
  14983. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14984. this._internalTexturesCache.push(texture);
  14985. return texture;
  14986. };
  14987. /** @hidden */
  14988. Engine.prototype._unpackFlipY = function (value) {
  14989. if (this._unpackFlipYCached !== value) {
  14990. this._unpackFlipYCached = value;
  14991. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14992. }
  14993. };
  14994. /**
  14995. * Creates a dynamic texture
  14996. * @param width defines the width of the texture
  14997. * @param height defines the height of the texture
  14998. * @param generateMipMaps defines if the engine should generate the mip levels
  14999. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15000. * @returns the dynamic texture inside an InternalTexture
  15001. */
  15002. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15003. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15004. texture.baseWidth = width;
  15005. texture.baseHeight = height;
  15006. if (generateMipMaps) {
  15007. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15008. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15009. }
  15010. // this.resetTextureCache();
  15011. texture.width = width;
  15012. texture.height = height;
  15013. texture.isReady = false;
  15014. texture.generateMipMaps = generateMipMaps;
  15015. texture.samplingMode = samplingMode;
  15016. this.updateTextureSamplingMode(samplingMode, texture);
  15017. this._internalTexturesCache.push(texture);
  15018. return texture;
  15019. };
  15020. /**
  15021. * Update the sampling mode of a given texture
  15022. * @param samplingMode defines the required sampling mode
  15023. * @param texture defines the texture to update
  15024. */
  15025. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15026. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  15027. if (texture.isCube) {
  15028. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15029. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15030. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15031. }
  15032. else if (texture.is3D) {
  15033. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15034. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15035. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15036. }
  15037. else {
  15038. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15039. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15040. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15041. }
  15042. texture.samplingMode = samplingMode;
  15043. };
  15044. /**
  15045. * Update the content of a dynamic texture
  15046. * @param texture defines the texture to update
  15047. * @param canvas defines the canvas containing the source
  15048. * @param invertY defines if data must be stored with Y axis inverted
  15049. * @param premulAlpha defines if alpha is stored as premultiplied
  15050. * @param format defines the format of the data
  15051. */
  15052. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15053. if (premulAlpha === void 0) { premulAlpha = false; }
  15054. if (!texture) {
  15055. return;
  15056. }
  15057. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15058. this._unpackFlipY(invertY);
  15059. if (premulAlpha) {
  15060. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15061. }
  15062. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15063. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15064. if (texture.generateMipMaps) {
  15065. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15066. }
  15067. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15068. if (premulAlpha) {
  15069. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15070. }
  15071. texture.isReady = true;
  15072. };
  15073. /**
  15074. * Update a video texture
  15075. * @param texture defines the texture to update
  15076. * @param video defines the video element to use
  15077. * @param invertY defines if data must be stored with Y axis inverted
  15078. */
  15079. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15080. if (!texture || texture._isDisabled) {
  15081. return;
  15082. }
  15083. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15084. this._unpackFlipY(!invertY); // Video are upside down by default
  15085. try {
  15086. // Testing video texture support
  15087. if (this._videoTextureSupported === undefined) {
  15088. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15089. if (this._gl.getError() !== 0) {
  15090. this._videoTextureSupported = false;
  15091. }
  15092. else {
  15093. this._videoTextureSupported = true;
  15094. }
  15095. }
  15096. // Copy video through the current working canvas if video texture is not supported
  15097. if (!this._videoTextureSupported) {
  15098. if (!texture._workingCanvas) {
  15099. texture._workingCanvas = document.createElement("canvas");
  15100. var context = texture._workingCanvas.getContext("2d");
  15101. if (!context) {
  15102. throw new Error("Unable to get 2d context");
  15103. }
  15104. texture._workingContext = context;
  15105. texture._workingCanvas.width = texture.width;
  15106. texture._workingCanvas.height = texture.height;
  15107. }
  15108. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15109. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15110. }
  15111. else {
  15112. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15113. }
  15114. if (texture.generateMipMaps) {
  15115. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15116. }
  15117. if (!wasPreviouslyBound) {
  15118. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15119. }
  15120. // this.resetTextureCache();
  15121. texture.isReady = true;
  15122. }
  15123. catch (ex) {
  15124. // Something unexpected
  15125. // Let's disable the texture
  15126. texture._isDisabled = true;
  15127. }
  15128. };
  15129. /**
  15130. * Updates a depth texture Comparison Mode and Function.
  15131. * If the comparison Function is equal to 0, the mode will be set to none.
  15132. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15133. * @param texture The texture to set the comparison function for
  15134. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15135. */
  15136. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15137. if (this.webGLVersion === 1) {
  15138. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15139. return;
  15140. }
  15141. var gl = this._gl;
  15142. if (texture.isCube) {
  15143. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15144. if (comparisonFunction === 0) {
  15145. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15146. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15147. }
  15148. else {
  15149. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15151. }
  15152. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15153. }
  15154. else {
  15155. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15156. if (comparisonFunction === 0) {
  15157. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15158. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15159. }
  15160. else {
  15161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15163. }
  15164. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15165. }
  15166. texture._comparisonFunction = comparisonFunction;
  15167. };
  15168. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15169. var width = size.width || size;
  15170. var height = size.height || size;
  15171. internalTexture.baseWidth = width;
  15172. internalTexture.baseHeight = height;
  15173. internalTexture.width = width;
  15174. internalTexture.height = height;
  15175. internalTexture.isReady = true;
  15176. internalTexture.samples = 1;
  15177. internalTexture.generateMipMaps = false;
  15178. internalTexture._generateDepthBuffer = true;
  15179. internalTexture._generateStencilBuffer = generateStencil;
  15180. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15181. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15182. internalTexture._comparisonFunction = comparisonFunction;
  15183. var gl = this._gl;
  15184. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15185. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15186. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15187. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15188. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15189. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15190. if (comparisonFunction === 0) {
  15191. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15192. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15193. }
  15194. else {
  15195. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15196. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15197. }
  15198. };
  15199. /**
  15200. * Creates a depth stencil texture.
  15201. * This is only available in WebGL 2 or with the depth texture extension available.
  15202. * @param size The size of face edge in the texture.
  15203. * @param options The options defining the texture.
  15204. * @returns The texture
  15205. */
  15206. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15207. if (options.isCube) {
  15208. var width = size.width || size;
  15209. return this._createDepthStencilCubeTexture(width, options);
  15210. }
  15211. else {
  15212. return this._createDepthStencilTexture(size, options);
  15213. }
  15214. };
  15215. /**
  15216. * Creates a depth stencil texture.
  15217. * This is only available in WebGL 2 or with the depth texture extension available.
  15218. * @param size The size of face edge in the texture.
  15219. * @param options The options defining the texture.
  15220. * @returns The texture
  15221. */
  15222. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15223. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15224. if (!this._caps.depthTextureExtension) {
  15225. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15226. return internalTexture;
  15227. }
  15228. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15229. var gl = this._gl;
  15230. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15231. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15232. if (this.webGLVersion > 1) {
  15233. if (internalOptions.generateStencil) {
  15234. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15235. }
  15236. else {
  15237. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15238. }
  15239. }
  15240. else {
  15241. if (internalOptions.generateStencil) {
  15242. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15243. }
  15244. else {
  15245. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15246. }
  15247. }
  15248. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15249. return internalTexture;
  15250. };
  15251. /**
  15252. * Creates a depth stencil cube texture.
  15253. * This is only available in WebGL 2.
  15254. * @param size The size of face edge in the cube texture.
  15255. * @param options The options defining the cube texture.
  15256. * @returns The cube texture
  15257. */
  15258. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15259. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15260. internalTexture.isCube = true;
  15261. if (this.webGLVersion === 1) {
  15262. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15263. return internalTexture;
  15264. }
  15265. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15266. var gl = this._gl;
  15267. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15268. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15269. // Create the depth/stencil buffer
  15270. for (var face = 0; face < 6; face++) {
  15271. if (internalOptions.generateStencil) {
  15272. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15273. }
  15274. else {
  15275. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15276. }
  15277. }
  15278. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15279. return internalTexture;
  15280. };
  15281. /**
  15282. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15283. * @param renderTarget The render target to set the frame buffer for
  15284. */
  15285. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15286. // Create the framebuffer
  15287. var internalTexture = renderTarget.getInternalTexture();
  15288. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15289. return;
  15290. }
  15291. var gl = this._gl;
  15292. var depthStencilTexture = renderTarget.depthStencilTexture;
  15293. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15294. if (depthStencilTexture.isCube) {
  15295. if (depthStencilTexture._generateStencilBuffer) {
  15296. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15297. }
  15298. else {
  15299. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15300. }
  15301. }
  15302. else {
  15303. if (depthStencilTexture._generateStencilBuffer) {
  15304. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15305. }
  15306. else {
  15307. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15308. }
  15309. }
  15310. this.bindUnboundFramebuffer(null);
  15311. };
  15312. /**
  15313. * Creates a new render target texture
  15314. * @param size defines the size of the texture
  15315. * @param options defines the options used to create the texture
  15316. * @returns a new render target texture stored in an InternalTexture
  15317. */
  15318. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15319. var fullOptions = new RenderTargetCreationOptions();
  15320. if (options !== undefined && typeof options === "object") {
  15321. fullOptions.generateMipMaps = options.generateMipMaps;
  15322. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15323. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15324. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15325. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15326. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15327. }
  15328. else {
  15329. fullOptions.generateMipMaps = options;
  15330. fullOptions.generateDepthBuffer = true;
  15331. fullOptions.generateStencilBuffer = false;
  15332. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15333. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15334. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15335. }
  15336. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15337. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15338. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15339. }
  15340. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15341. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15342. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15343. }
  15344. var gl = this._gl;
  15345. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15346. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15347. var width = size.width || size;
  15348. var height = size.height || size;
  15349. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15350. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15351. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15352. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15353. }
  15354. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15355. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15356. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15357. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15358. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15359. // Create the framebuffer
  15360. var currentFrameBuffer = this._currentFramebuffer;
  15361. var framebuffer = gl.createFramebuffer();
  15362. this.bindUnboundFramebuffer(framebuffer);
  15363. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15364. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15365. if (fullOptions.generateMipMaps) {
  15366. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15367. }
  15368. // Unbind
  15369. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15370. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15371. this.bindUnboundFramebuffer(currentFrameBuffer);
  15372. texture._framebuffer = framebuffer;
  15373. texture.baseWidth = width;
  15374. texture.baseHeight = height;
  15375. texture.width = width;
  15376. texture.height = height;
  15377. texture.isReady = true;
  15378. texture.samples = 1;
  15379. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15380. texture.samplingMode = fullOptions.samplingMode;
  15381. texture.type = fullOptions.type;
  15382. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15383. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15384. // this.resetTextureCache();
  15385. this._internalTexturesCache.push(texture);
  15386. return texture;
  15387. };
  15388. /**
  15389. * Create a multi render target texture
  15390. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15391. * @param size defines the size of the texture
  15392. * @param options defines the creation options
  15393. * @returns the cube texture as an InternalTexture
  15394. */
  15395. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15396. var generateMipMaps = false;
  15397. var generateDepthBuffer = true;
  15398. var generateStencilBuffer = false;
  15399. var generateDepthTexture = false;
  15400. var textureCount = 1;
  15401. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15402. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15403. var types = new Array();
  15404. var samplingModes = new Array();
  15405. if (options !== undefined) {
  15406. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15407. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15408. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15409. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15410. textureCount = options.textureCount || 1;
  15411. if (options.types) {
  15412. types = options.types;
  15413. }
  15414. if (options.samplingModes) {
  15415. samplingModes = options.samplingModes;
  15416. }
  15417. }
  15418. var gl = this._gl;
  15419. // Create the framebuffer
  15420. var framebuffer = gl.createFramebuffer();
  15421. this.bindUnboundFramebuffer(framebuffer);
  15422. var width = size.width || size;
  15423. var height = size.height || size;
  15424. var textures = [];
  15425. var attachments = [];
  15426. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15427. for (var i = 0; i < textureCount; i++) {
  15428. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15429. var type = types[i] || defaultType;
  15430. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15431. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15432. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15433. }
  15434. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15435. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15436. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15437. }
  15438. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15439. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15440. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15441. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15442. }
  15443. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15444. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15445. textures.push(texture);
  15446. attachments.push(attachment);
  15447. gl.activeTexture(gl["TEXTURE" + i]);
  15448. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15449. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15450. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15451. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15453. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15454. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15455. if (generateMipMaps) {
  15456. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15457. }
  15458. // Unbind
  15459. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15460. texture._framebuffer = framebuffer;
  15461. texture._depthStencilBuffer = depthStencilBuffer;
  15462. texture.baseWidth = width;
  15463. texture.baseHeight = height;
  15464. texture.width = width;
  15465. texture.height = height;
  15466. texture.isReady = true;
  15467. texture.samples = 1;
  15468. texture.generateMipMaps = generateMipMaps;
  15469. texture.samplingMode = samplingMode;
  15470. texture.type = type;
  15471. texture._generateDepthBuffer = generateDepthBuffer;
  15472. texture._generateStencilBuffer = generateStencilBuffer;
  15473. texture._attachments = attachments;
  15474. this._internalTexturesCache.push(texture);
  15475. }
  15476. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15477. // Depth texture
  15478. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15479. gl.activeTexture(gl.TEXTURE0);
  15480. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15481. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15482. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15483. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15484. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15485. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  15486. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15487. depthTexture._framebuffer = framebuffer;
  15488. depthTexture.baseWidth = width;
  15489. depthTexture.baseHeight = height;
  15490. depthTexture.width = width;
  15491. depthTexture.height = height;
  15492. depthTexture.isReady = true;
  15493. depthTexture.samples = 1;
  15494. depthTexture.generateMipMaps = generateMipMaps;
  15495. depthTexture.samplingMode = gl.NEAREST;
  15496. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15497. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15498. textures.push(depthTexture);
  15499. this._internalTexturesCache.push(depthTexture);
  15500. }
  15501. gl.drawBuffers(attachments);
  15502. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15503. this.bindUnboundFramebuffer(null);
  15504. this.resetTextureCache();
  15505. return textures;
  15506. };
  15507. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15508. if (samples === void 0) { samples = 1; }
  15509. var depthStencilBuffer = null;
  15510. var gl = this._gl;
  15511. // Create the depth/stencil buffer
  15512. if (generateStencilBuffer) {
  15513. depthStencilBuffer = gl.createRenderbuffer();
  15514. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15515. if (samples > 1) {
  15516. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15517. }
  15518. else {
  15519. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15520. }
  15521. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15522. }
  15523. else if (generateDepthBuffer) {
  15524. depthStencilBuffer = gl.createRenderbuffer();
  15525. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15526. if (samples > 1) {
  15527. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15528. }
  15529. else {
  15530. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15531. }
  15532. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15533. }
  15534. return depthStencilBuffer;
  15535. };
  15536. /**
  15537. * Updates the sample count of a render target texture
  15538. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15539. * @param texture defines the texture to update
  15540. * @param samples defines the sample count to set
  15541. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15542. */
  15543. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15544. if (this.webGLVersion < 2 || !texture) {
  15545. return 1;
  15546. }
  15547. if (texture.samples === samples) {
  15548. return samples;
  15549. }
  15550. var gl = this._gl;
  15551. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15552. // Dispose previous render buffers
  15553. if (texture._depthStencilBuffer) {
  15554. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15555. texture._depthStencilBuffer = null;
  15556. }
  15557. if (texture._MSAAFramebuffer) {
  15558. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15559. texture._MSAAFramebuffer = null;
  15560. }
  15561. if (texture._MSAARenderBuffer) {
  15562. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15563. texture._MSAARenderBuffer = null;
  15564. }
  15565. if (samples > 1) {
  15566. var framebuffer = gl.createFramebuffer();
  15567. if (!framebuffer) {
  15568. throw new Error("Unable to create multi sampled framebuffer");
  15569. }
  15570. texture._MSAAFramebuffer = framebuffer;
  15571. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15572. var colorRenderbuffer = gl.createRenderbuffer();
  15573. if (!colorRenderbuffer) {
  15574. throw new Error("Unable to create multi sampled framebuffer");
  15575. }
  15576. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15577. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15578. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15579. texture._MSAARenderBuffer = colorRenderbuffer;
  15580. }
  15581. else {
  15582. this.bindUnboundFramebuffer(texture._framebuffer);
  15583. }
  15584. texture.samples = samples;
  15585. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15586. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15587. this.bindUnboundFramebuffer(null);
  15588. return samples;
  15589. };
  15590. /**
  15591. * Update the sample count for a given multiple render target texture
  15592. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15593. * @param textures defines the textures to update
  15594. * @param samples defines the sample count to set
  15595. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15596. */
  15597. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15598. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15599. return 1;
  15600. }
  15601. if (textures[0].samples === samples) {
  15602. return samples;
  15603. }
  15604. var gl = this._gl;
  15605. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15606. // Dispose previous render buffers
  15607. if (textures[0]._depthStencilBuffer) {
  15608. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15609. textures[0]._depthStencilBuffer = null;
  15610. }
  15611. if (textures[0]._MSAAFramebuffer) {
  15612. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15613. textures[0]._MSAAFramebuffer = null;
  15614. }
  15615. for (var i = 0; i < textures.length; i++) {
  15616. if (textures[i]._MSAARenderBuffer) {
  15617. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15618. textures[i]._MSAARenderBuffer = null;
  15619. }
  15620. }
  15621. if (samples > 1) {
  15622. var framebuffer = gl.createFramebuffer();
  15623. if (!framebuffer) {
  15624. throw new Error("Unable to create multi sampled framebuffer");
  15625. }
  15626. this.bindUnboundFramebuffer(framebuffer);
  15627. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15628. var attachments = [];
  15629. for (var i = 0; i < textures.length; i++) {
  15630. var texture = textures[i];
  15631. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15632. var colorRenderbuffer = gl.createRenderbuffer();
  15633. if (!colorRenderbuffer) {
  15634. throw new Error("Unable to create multi sampled framebuffer");
  15635. }
  15636. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15637. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15638. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15639. texture._MSAAFramebuffer = framebuffer;
  15640. texture._MSAARenderBuffer = colorRenderbuffer;
  15641. texture.samples = samples;
  15642. texture._depthStencilBuffer = depthStencilBuffer;
  15643. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15644. attachments.push(attachment);
  15645. }
  15646. gl.drawBuffers(attachments);
  15647. }
  15648. else {
  15649. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15650. }
  15651. this.bindUnboundFramebuffer(null);
  15652. return samples;
  15653. };
  15654. /** @hidden */
  15655. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15656. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15657. };
  15658. /** @hidden */
  15659. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15660. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15661. };
  15662. /** @hidden */
  15663. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15664. var gl = this._gl;
  15665. var textureType = this._getWebGLTextureType(texture.type);
  15666. var format = this._getInternalFormat(texture.format);
  15667. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15668. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15669. this._bindTextureDirectly(bindTarget, texture, true);
  15670. this._unpackFlipY(texture.invertY);
  15671. var target = gl.TEXTURE_2D;
  15672. if (texture.isCube) {
  15673. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15674. }
  15675. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15676. this._bindTextureDirectly(bindTarget, null, true);
  15677. };
  15678. /**
  15679. * Creates a new render target cube texture
  15680. * @param size defines the size of the texture
  15681. * @param options defines the options used to create the texture
  15682. * @returns a new render target cube texture stored in an InternalTexture
  15683. */
  15684. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15685. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15686. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15687. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15688. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15689. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15690. }
  15691. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15692. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15693. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15694. }
  15695. var gl = this._gl;
  15696. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15697. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15698. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15699. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15700. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15701. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15702. }
  15703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15707. for (var face = 0; face < 6; face++) {
  15708. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15709. }
  15710. // Create the framebuffer
  15711. var framebuffer = gl.createFramebuffer();
  15712. this.bindUnboundFramebuffer(framebuffer);
  15713. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15714. // MipMaps
  15715. if (fullOptions.generateMipMaps) {
  15716. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15717. }
  15718. // Unbind
  15719. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15720. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15721. this.bindUnboundFramebuffer(null);
  15722. texture._framebuffer = framebuffer;
  15723. texture.width = size;
  15724. texture.height = size;
  15725. texture.isReady = true;
  15726. texture.isCube = true;
  15727. texture.samples = 1;
  15728. texture.generateMipMaps = fullOptions.generateMipMaps;
  15729. texture.samplingMode = fullOptions.samplingMode;
  15730. texture.type = fullOptions.type;
  15731. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15732. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15733. this._internalTexturesCache.push(texture);
  15734. return texture;
  15735. };
  15736. /**
  15737. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15738. * @param rootUrl defines the url where the file to load is located
  15739. * @param scene defines the current scene
  15740. * @param lodScale defines scale to apply to the mip map selection
  15741. * @param lodOffset defines offset to apply to the mip map selection
  15742. * @param onLoad defines an optional callback raised when the texture is loaded
  15743. * @param onError defines an optional callback raised if there is an issue to load the texture
  15744. * @param format defines the format of the data
  15745. * @param forcedExtension defines the extension to use to pick the right loader
  15746. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15747. * @returns the cube texture as an InternalTexture
  15748. */
  15749. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15750. var _this = this;
  15751. if (onLoad === void 0) { onLoad = null; }
  15752. if (onError === void 0) { onError = null; }
  15753. if (forcedExtension === void 0) { forcedExtension = null; }
  15754. if (createPolynomials === void 0) { createPolynomials = true; }
  15755. var callback = function (loadData) {
  15756. if (!loadData) {
  15757. if (onLoad) {
  15758. onLoad(null);
  15759. }
  15760. return;
  15761. }
  15762. var texture = loadData.texture;
  15763. if (!createPolynomials) {
  15764. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15765. }
  15766. else if (loadData.info.sphericalPolynomial) {
  15767. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15768. }
  15769. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15770. if (_this._caps.textureLOD) {
  15771. // Do not add extra process if texture lod is supported.
  15772. if (onLoad) {
  15773. onLoad(texture);
  15774. }
  15775. return;
  15776. }
  15777. var mipSlices = 3;
  15778. var gl = _this._gl;
  15779. var width = loadData.width;
  15780. if (!width) {
  15781. return;
  15782. }
  15783. var textures = [];
  15784. for (var i = 0; i < mipSlices; i++) {
  15785. //compute LOD from even spacing in smoothness (matching shader calculation)
  15786. var smoothness = i / (mipSlices - 1);
  15787. var roughness = 1 - smoothness;
  15788. var minLODIndex = lodOffset; // roughness = 0
  15789. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15790. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15791. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15792. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15793. glTextureFromLod.isCube = true;
  15794. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15799. if (loadData.isDDS) {
  15800. var info = loadData.info;
  15801. var data = loadData.data;
  15802. _this._unpackFlipY(info.isCompressed);
  15803. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15804. }
  15805. else {
  15806. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15807. }
  15808. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15809. // Wrap in a base texture for easy binding.
  15810. var lodTexture = new BABYLON.BaseTexture(scene);
  15811. lodTexture.isCube = true;
  15812. lodTexture._texture = glTextureFromLod;
  15813. glTextureFromLod.isReady = true;
  15814. textures.push(lodTexture);
  15815. }
  15816. texture._lodTextureHigh = textures[2];
  15817. texture._lodTextureMid = textures[1];
  15818. texture._lodTextureLow = textures[0];
  15819. if (onLoad) {
  15820. onLoad(texture);
  15821. }
  15822. };
  15823. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15824. };
  15825. /**
  15826. * Creates a cube texture
  15827. * @param rootUrl defines the url where the files to load is located
  15828. * @param scene defines the current scene
  15829. * @param files defines the list of files to load (1 per face)
  15830. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15831. * @param onLoad defines an optional callback raised when the texture is loaded
  15832. * @param onError defines an optional callback raised if there is an issue to load the texture
  15833. * @param format defines the format of the data
  15834. * @param forcedExtension defines the extension to use to pick the right loader
  15835. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15836. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15837. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15838. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15839. * @returns the cube texture as an InternalTexture
  15840. */
  15841. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15842. var _this = this;
  15843. if (onLoad === void 0) { onLoad = null; }
  15844. if (onError === void 0) { onError = null; }
  15845. if (forcedExtension === void 0) { forcedExtension = null; }
  15846. if (createPolynomials === void 0) { createPolynomials = false; }
  15847. if (lodScale === void 0) { lodScale = 0; }
  15848. if (lodOffset === void 0) { lodOffset = 0; }
  15849. if (fallback === void 0) { fallback = null; }
  15850. var gl = this._gl;
  15851. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15852. texture.isCube = true;
  15853. texture.url = rootUrl;
  15854. texture.generateMipMaps = !noMipmap;
  15855. texture._lodGenerationScale = lodScale;
  15856. texture._lodGenerationOffset = lodOffset;
  15857. if (!this._doNotHandleContextLost) {
  15858. texture._extension = forcedExtension;
  15859. texture._files = files;
  15860. }
  15861. var isKTX = false;
  15862. var isDDS = false;
  15863. var isEnv = false;
  15864. var lastDot = rootUrl.lastIndexOf('.');
  15865. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15866. if (this._textureFormatInUse && !fallback) {
  15867. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15868. isKTX = true;
  15869. }
  15870. else {
  15871. isDDS = (extension === ".dds");
  15872. isEnv = (extension === ".env");
  15873. }
  15874. var onerror = function (request, exception) {
  15875. if (isKTX) {
  15876. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15877. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15878. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15879. }
  15880. if (onError && request) {
  15881. onError(request.status + " " + request.statusText, exception);
  15882. }
  15883. };
  15884. if (isKTX) {
  15885. this._loadFile(rootUrl, function (data) {
  15886. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15887. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15888. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15889. _this._unpackFlipY(true);
  15890. ktx.uploadLevels(_this._gl, !noMipmap);
  15891. _this.setCubeMapTextureParams(gl, loadMipmap);
  15892. texture.width = ktx.pixelWidth;
  15893. texture.height = ktx.pixelHeight;
  15894. texture.isReady = true;
  15895. }, undefined, undefined, true, onerror);
  15896. }
  15897. else if (isEnv) {
  15898. this._loadFile(rootUrl, function (data) {
  15899. data = data;
  15900. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15901. if (info) {
  15902. texture.width = info.width;
  15903. texture.height = info.width;
  15904. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15905. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15906. texture.isReady = true;
  15907. if (onLoad) {
  15908. onLoad();
  15909. }
  15910. });
  15911. }
  15912. else if (onError) {
  15913. onError("Can not parse the environment file", null);
  15914. }
  15915. }, undefined, undefined, true, onerror);
  15916. }
  15917. else if (isDDS) {
  15918. if (files && files.length === 6) {
  15919. this._cascadeLoadFiles(scene, function (imgs) {
  15920. var info;
  15921. var loadMipmap = false;
  15922. var width = 0;
  15923. for (var index = 0; index < imgs.length; index++) {
  15924. var data = imgs[index];
  15925. info = BABYLON.DDSTools.GetDDSInfo(data);
  15926. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15927. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15928. _this._unpackFlipY(info.isCompressed);
  15929. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15930. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15931. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15932. }
  15933. texture.width = info.width;
  15934. texture.height = info.height;
  15935. texture.type = info.textureType;
  15936. width = info.width;
  15937. }
  15938. _this.setCubeMapTextureParams(gl, loadMipmap);
  15939. texture.isReady = true;
  15940. if (onLoad) {
  15941. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15942. }
  15943. }, files, onError);
  15944. }
  15945. else {
  15946. this._loadFile(rootUrl, function (data) {
  15947. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15948. if (createPolynomials) {
  15949. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15950. }
  15951. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15952. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15953. _this._unpackFlipY(info.isCompressed);
  15954. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15955. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15956. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15957. }
  15958. _this.setCubeMapTextureParams(gl, loadMipmap);
  15959. texture.width = info.width;
  15960. texture.height = info.height;
  15961. texture.isReady = true;
  15962. texture.type = info.textureType;
  15963. if (onLoad) {
  15964. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15965. }
  15966. }, undefined, undefined, true, onerror);
  15967. }
  15968. }
  15969. else {
  15970. if (!files) {
  15971. throw new Error("Cannot load cubemap because files were not defined");
  15972. }
  15973. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15974. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15975. var height = width;
  15976. _this._prepareWorkingCanvas();
  15977. if (!_this._workingCanvas || !_this._workingContext) {
  15978. return;
  15979. }
  15980. _this._workingCanvas.width = width;
  15981. _this._workingCanvas.height = height;
  15982. var faces = [
  15983. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15984. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15985. ];
  15986. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15987. _this._unpackFlipY(false);
  15988. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15989. for (var index = 0; index < faces.length; index++) {
  15990. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15991. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15992. }
  15993. if (!noMipmap) {
  15994. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15995. }
  15996. _this.setCubeMapTextureParams(gl, !noMipmap);
  15997. texture.width = width;
  15998. texture.height = height;
  15999. texture.isReady = true;
  16000. if (format) {
  16001. texture.format = format;
  16002. }
  16003. texture.onLoadedObservable.notifyObservers(texture);
  16004. texture.onLoadedObservable.clear();
  16005. if (onLoad) {
  16006. onLoad();
  16007. }
  16008. }, files, onError);
  16009. }
  16010. this._internalTexturesCache.push(texture);
  16011. return texture;
  16012. };
  16013. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  16014. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16015. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16016. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16017. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16018. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16019. // this.resetTextureCache();
  16020. };
  16021. /**
  16022. * Update a raw cube texture
  16023. * @param texture defines the texture to udpdate
  16024. * @param data defines the data to store
  16025. * @param format defines the data format
  16026. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16027. * @param invertY defines if data must be stored with Y axis inverted
  16028. * @param compression defines the compression used (null by default)
  16029. * @param level defines which level of the texture to update
  16030. */
  16031. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16032. if (compression === void 0) { compression = null; }
  16033. if (level === void 0) { level = 0; }
  16034. texture._bufferViewArray = data;
  16035. texture.format = format;
  16036. texture.type = type;
  16037. texture.invertY = invertY;
  16038. texture._compression = compression;
  16039. var gl = this._gl;
  16040. var textureType = this._getWebGLTextureType(type);
  16041. var internalFormat = this._getInternalFormat(format);
  16042. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16043. var needConversion = false;
  16044. if (internalFormat === gl.RGB) {
  16045. internalFormat = gl.RGBA;
  16046. needConversion = true;
  16047. }
  16048. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16049. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16050. if (texture.width % 4 !== 0) {
  16051. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16052. }
  16053. // Data are known to be in +X +Y +Z -X -Y -Z
  16054. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16055. var faceData = data[faceIndex];
  16056. if (compression) {
  16057. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16058. }
  16059. else {
  16060. if (needConversion) {
  16061. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16062. }
  16063. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16064. }
  16065. }
  16066. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16067. if (isPot && texture.generateMipMaps && level === 0) {
  16068. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16069. }
  16070. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16071. // this.resetTextureCache();
  16072. texture.isReady = true;
  16073. };
  16074. /**
  16075. * Creates a new raw cube texture
  16076. * @param data defines the array of data to use to create each face
  16077. * @param size defines the size of the textures
  16078. * @param format defines the format of the data
  16079. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16080. * @param generateMipMaps defines if the engine should generate the mip levels
  16081. * @param invertY defines if data must be stored with Y axis inverted
  16082. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16083. * @param compression defines the compression used (null by default)
  16084. * @returns the cube texture as an InternalTexture
  16085. */
  16086. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16087. if (compression === void 0) { compression = null; }
  16088. var gl = this._gl;
  16089. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16090. texture.isCube = true;
  16091. texture.generateMipMaps = generateMipMaps;
  16092. texture.format = format;
  16093. texture.type = type;
  16094. if (!this._doNotHandleContextLost) {
  16095. texture._bufferViewArray = data;
  16096. }
  16097. var textureType = this._getWebGLTextureType(type);
  16098. var internalFormat = this._getInternalFormat(format);
  16099. if (internalFormat === gl.RGB) {
  16100. internalFormat = gl.RGBA;
  16101. }
  16102. var width = size;
  16103. var height = width;
  16104. texture.width = width;
  16105. texture.height = height;
  16106. // Double check on POT to generate Mips.
  16107. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16108. if (!isPot) {
  16109. generateMipMaps = false;
  16110. }
  16111. // Upload data if needed. The texture won't be ready until then.
  16112. if (data) {
  16113. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16114. }
  16115. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16116. // Filters
  16117. if (data && generateMipMaps) {
  16118. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16119. }
  16120. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16123. }
  16124. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16125. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16127. }
  16128. else {
  16129. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16130. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16131. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16132. }
  16133. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16134. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16135. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16136. return texture;
  16137. };
  16138. /**
  16139. * Creates a new raw cube texture from a specified url
  16140. * @param url defines the url where the data is located
  16141. * @param scene defines the current scene
  16142. * @param size defines the size of the textures
  16143. * @param format defines the format of the data
  16144. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16145. * @param noMipmap defines if the engine should avoid generating the mip levels
  16146. * @param callback defines a callback used to extract texture data from loaded data
  16147. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16148. * @param onLoad defines a callback called when texture is loaded
  16149. * @param onError defines a callback called if there is an error
  16150. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16151. * @param invertY defines if data must be stored with Y axis inverted
  16152. * @returns the cube texture as an InternalTexture
  16153. */
  16154. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16155. var _this = this;
  16156. if (onLoad === void 0) { onLoad = null; }
  16157. if (onError === void 0) { onError = null; }
  16158. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16159. if (invertY === void 0) { invertY = false; }
  16160. var gl = this._gl;
  16161. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16162. scene._addPendingData(texture);
  16163. texture.url = url;
  16164. this._internalTexturesCache.push(texture);
  16165. var onerror = function (request, exception) {
  16166. scene._removePendingData(texture);
  16167. if (onError && request) {
  16168. onError(request.status + " " + request.statusText, exception);
  16169. }
  16170. };
  16171. var internalCallback = function (data) {
  16172. var width = texture.width;
  16173. var faceDataArrays = callback(data);
  16174. if (!faceDataArrays) {
  16175. return;
  16176. }
  16177. if (mipmapGenerator) {
  16178. var textureType = _this._getWebGLTextureType(type);
  16179. var internalFormat = _this._getInternalFormat(format);
  16180. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16181. var needConversion = false;
  16182. if (internalFormat === gl.RGB) {
  16183. internalFormat = gl.RGBA;
  16184. needConversion = true;
  16185. }
  16186. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16187. _this._unpackFlipY(false);
  16188. var mipData = mipmapGenerator(faceDataArrays);
  16189. for (var level = 0; level < mipData.length; level++) {
  16190. var mipSize = width >> level;
  16191. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16192. var mipFaceData = mipData[level][faceIndex];
  16193. if (needConversion) {
  16194. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16195. }
  16196. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16197. }
  16198. }
  16199. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16200. }
  16201. else {
  16202. texture.generateMipMaps = !noMipmap;
  16203. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16204. }
  16205. texture.isReady = true;
  16206. // this.resetTextureCache();
  16207. scene._removePendingData(texture);
  16208. if (onLoad) {
  16209. onLoad();
  16210. }
  16211. };
  16212. this._loadFile(url, function (data) {
  16213. internalCallback(data);
  16214. }, undefined, scene.database, true, onerror);
  16215. return texture;
  16216. };
  16217. ;
  16218. /**
  16219. * Update a raw 3D texture
  16220. * @param texture defines the texture to update
  16221. * @param data defines the data to store
  16222. * @param format defines the data format
  16223. * @param invertY defines if data must be stored with Y axis inverted
  16224. * @param compression defines the used compression (can be null)
  16225. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16226. */
  16227. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16228. if (compression === void 0) { compression = null; }
  16229. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16230. var internalType = this._getWebGLTextureType(textureType);
  16231. var internalFormat = this._getInternalFormat(format);
  16232. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16233. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16234. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16235. if (!this._doNotHandleContextLost) {
  16236. texture._bufferView = data;
  16237. texture.format = format;
  16238. texture.invertY = invertY;
  16239. texture._compression = compression;
  16240. }
  16241. if (texture.width % 4 !== 0) {
  16242. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16243. }
  16244. if (compression && data) {
  16245. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16246. }
  16247. else {
  16248. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16249. }
  16250. if (texture.generateMipMaps) {
  16251. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16252. }
  16253. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16254. // this.resetTextureCache();
  16255. texture.isReady = true;
  16256. };
  16257. /**
  16258. * Creates a new raw 3D texture
  16259. * @param data defines the data used to create the texture
  16260. * @param width defines the width of the texture
  16261. * @param height defines the height of the texture
  16262. * @param depth defines the depth of the texture
  16263. * @param format defines the format of the texture
  16264. * @param generateMipMaps defines if the engine must generate mip levels
  16265. * @param invertY defines if data must be stored with Y axis inverted
  16266. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16267. * @param compression defines the compressed used (can be null)
  16268. * @param textureType defines the compressed used (can be null)
  16269. * @returns a new raw 3D texture (stored in an InternalTexture)
  16270. */
  16271. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16272. if (compression === void 0) { compression = null; }
  16273. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16274. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16275. texture.baseWidth = width;
  16276. texture.baseHeight = height;
  16277. texture.baseDepth = depth;
  16278. texture.width = width;
  16279. texture.height = height;
  16280. texture.depth = depth;
  16281. texture.format = format;
  16282. texture.type = textureType;
  16283. texture.generateMipMaps = generateMipMaps;
  16284. texture.samplingMode = samplingMode;
  16285. texture.is3D = true;
  16286. if (!this._doNotHandleContextLost) {
  16287. texture._bufferView = data;
  16288. }
  16289. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16290. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16291. // Filters
  16292. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16293. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16294. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16295. if (generateMipMaps) {
  16296. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16297. }
  16298. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16299. this._internalTexturesCache.push(texture);
  16300. return texture;
  16301. };
  16302. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16303. var gl = this._gl;
  16304. if (!gl) {
  16305. return;
  16306. }
  16307. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16308. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16310. if (!noMipmap && !isCompressed) {
  16311. gl.generateMipmap(gl.TEXTURE_2D);
  16312. }
  16313. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16314. // this.resetTextureCache();
  16315. if (scene) {
  16316. scene._removePendingData(texture);
  16317. }
  16318. texture.onLoadedObservable.notifyObservers(texture);
  16319. texture.onLoadedObservable.clear();
  16320. };
  16321. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16322. var _this = this;
  16323. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16324. var maxTextureSize = this.getCaps().maxTextureSize;
  16325. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16326. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16327. var gl = this._gl;
  16328. if (!gl) {
  16329. return;
  16330. }
  16331. if (!texture._webGLTexture) {
  16332. // this.resetTextureCache();
  16333. if (scene) {
  16334. scene._removePendingData(texture);
  16335. }
  16336. return;
  16337. }
  16338. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16339. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16340. texture.baseWidth = width;
  16341. texture.baseHeight = height;
  16342. texture.width = potWidth;
  16343. texture.height = potHeight;
  16344. texture.isReady = true;
  16345. if (processFunction(potWidth, potHeight, function () {
  16346. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16347. })) {
  16348. // Returning as texture needs extra async steps
  16349. return;
  16350. }
  16351. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16352. };
  16353. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16354. // Create new RGBA data container.
  16355. var rgbaData;
  16356. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16357. rgbaData = new Float32Array(width * height * 4);
  16358. }
  16359. else {
  16360. rgbaData = new Uint32Array(width * height * 4);
  16361. }
  16362. // Convert each pixel.
  16363. for (var x = 0; x < width; x++) {
  16364. for (var y = 0; y < height; y++) {
  16365. var index = (y * width + x) * 3;
  16366. var newIndex = (y * width + x) * 4;
  16367. // Map Old Value to new value.
  16368. rgbaData[newIndex + 0] = rgbData[index + 0];
  16369. rgbaData[newIndex + 1] = rgbData[index + 1];
  16370. rgbaData[newIndex + 2] = rgbData[index + 2];
  16371. // Add fully opaque alpha channel.
  16372. rgbaData[newIndex + 3] = 1;
  16373. }
  16374. }
  16375. return rgbaData;
  16376. };
  16377. /** @hidden */
  16378. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16379. var gl = this._gl;
  16380. if (texture._framebuffer) {
  16381. gl.deleteFramebuffer(texture._framebuffer);
  16382. texture._framebuffer = null;
  16383. }
  16384. if (texture._depthStencilBuffer) {
  16385. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16386. texture._depthStencilBuffer = null;
  16387. }
  16388. if (texture._MSAAFramebuffer) {
  16389. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16390. texture._MSAAFramebuffer = null;
  16391. }
  16392. if (texture._MSAARenderBuffer) {
  16393. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16394. texture._MSAARenderBuffer = null;
  16395. }
  16396. };
  16397. /** @hidden */
  16398. Engine.prototype._releaseTexture = function (texture) {
  16399. var gl = this._gl;
  16400. this._releaseFramebufferObjects(texture);
  16401. gl.deleteTexture(texture._webGLTexture);
  16402. // Unbind channels
  16403. this.unbindAllTextures();
  16404. var index = this._internalTexturesCache.indexOf(texture);
  16405. if (index !== -1) {
  16406. this._internalTexturesCache.splice(index, 1);
  16407. }
  16408. // Integrated fixed lod samplers.
  16409. if (texture._lodTextureHigh) {
  16410. texture._lodTextureHigh.dispose();
  16411. }
  16412. if (texture._lodTextureMid) {
  16413. texture._lodTextureMid.dispose();
  16414. }
  16415. if (texture._lodTextureLow) {
  16416. texture._lodTextureLow.dispose();
  16417. }
  16418. // Set output texture of post process to null if the texture has been released/disposed
  16419. this.scenes.forEach(function (scene) {
  16420. scene.postProcesses.forEach(function (postProcess) {
  16421. if (postProcess._outputTexture == texture) {
  16422. postProcess._outputTexture = null;
  16423. }
  16424. });
  16425. scene.cameras.forEach(function (camera) {
  16426. camera._postProcesses.forEach(function (postProcess) {
  16427. if (postProcess) {
  16428. if (postProcess._outputTexture == texture) {
  16429. postProcess._outputTexture = null;
  16430. }
  16431. }
  16432. });
  16433. });
  16434. });
  16435. };
  16436. Engine.prototype.setProgram = function (program) {
  16437. if (this._currentProgram !== program) {
  16438. this._gl.useProgram(program);
  16439. this._currentProgram = program;
  16440. }
  16441. };
  16442. /**
  16443. * Binds an effect to the webGL context
  16444. * @param effect defines the effect to bind
  16445. */
  16446. Engine.prototype.bindSamplers = function (effect) {
  16447. this.setProgram(effect.getProgram());
  16448. var samplers = effect.getSamplers();
  16449. for (var index = 0; index < samplers.length; index++) {
  16450. var uniform = effect.getUniform(samplers[index]);
  16451. if (uniform) {
  16452. this._boundUniforms[index] = uniform;
  16453. }
  16454. }
  16455. this._currentEffect = null;
  16456. };
  16457. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16458. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16459. return;
  16460. }
  16461. // Remove
  16462. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16463. // Bind last to it
  16464. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16465. // Bind to dummy
  16466. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16467. };
  16468. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16469. if (!internalTexture) {
  16470. return -1;
  16471. }
  16472. internalTexture._initialSlot = channel;
  16473. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16474. if (channel !== internalTexture._designatedSlot) {
  16475. this._textureCollisions.addCount(1, false);
  16476. }
  16477. }
  16478. else {
  16479. if (channel !== internalTexture._designatedSlot) {
  16480. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16481. return internalTexture._designatedSlot;
  16482. }
  16483. else {
  16484. // No slot for this texture, let's pick a new one (if we find a free slot)
  16485. if (this._nextFreeTextureSlots.length) {
  16486. return this._nextFreeTextureSlots[0];
  16487. }
  16488. // We need to recycle the oldest bound texture, sorry.
  16489. this._textureCollisions.addCount(1, false);
  16490. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16491. }
  16492. }
  16493. }
  16494. return channel;
  16495. };
  16496. Engine.prototype._linkTrackers = function (previous, next) {
  16497. previous.next = next;
  16498. next.previous = previous;
  16499. };
  16500. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16501. var currentSlot = internalTexture._designatedSlot;
  16502. if (currentSlot === -1) {
  16503. return -1;
  16504. }
  16505. internalTexture._designatedSlot = -1;
  16506. if (this.disableTextureBindingOptimization) {
  16507. return -1;
  16508. }
  16509. // Remove from bound list
  16510. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16511. // Free the slot
  16512. this._boundTexturesCache[currentSlot] = null;
  16513. this._nextFreeTextureSlots.push(currentSlot);
  16514. return currentSlot;
  16515. };
  16516. Engine.prototype._activateCurrentTexture = function () {
  16517. if (this._currentTextureChannel !== this._activeChannel) {
  16518. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16519. this._currentTextureChannel = this._activeChannel;
  16520. }
  16521. };
  16522. /** @hidden */
  16523. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16524. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16525. if (force === void 0) { force = false; }
  16526. var wasPreviouslyBound = false;
  16527. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16528. this._activeChannel = texture._designatedSlot;
  16529. }
  16530. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16531. var isTextureForRendering = texture && texture._initialSlot > -1;
  16532. if (currentTextureBound !== texture || force) {
  16533. if (currentTextureBound) {
  16534. this._removeDesignatedSlot(currentTextureBound);
  16535. }
  16536. this._activateCurrentTexture();
  16537. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16538. this._boundTexturesCache[this._activeChannel] = texture;
  16539. if (texture) {
  16540. if (!this.disableTextureBindingOptimization) {
  16541. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16542. if (slotIndex > -1) {
  16543. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16544. }
  16545. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16546. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16547. }
  16548. texture._designatedSlot = this._activeChannel;
  16549. }
  16550. }
  16551. else if (forTextureDataUpdate) {
  16552. wasPreviouslyBound = true;
  16553. this._activateCurrentTexture();
  16554. }
  16555. if (isTextureForRendering && !forTextureDataUpdate) {
  16556. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16557. }
  16558. return wasPreviouslyBound;
  16559. };
  16560. /** @hidden */
  16561. Engine.prototype._bindTexture = function (channel, texture) {
  16562. if (channel < 0) {
  16563. return;
  16564. }
  16565. if (texture) {
  16566. channel = this._getCorrectTextureChannel(channel, texture);
  16567. }
  16568. this._activeChannel = channel;
  16569. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16570. };
  16571. /**
  16572. * Sets a texture to the webGL context from a postprocess
  16573. * @param channel defines the channel to use
  16574. * @param postProcess defines the source postprocess
  16575. */
  16576. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16577. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16578. };
  16579. /**
  16580. * Binds the output of the passed in post process to the texture channel specified
  16581. * @param channel The channel the texture should be bound to
  16582. * @param postProcess The post process which's output should be bound
  16583. */
  16584. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16585. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16586. };
  16587. /**
  16588. * Unbind all textures from the webGL context
  16589. */
  16590. Engine.prototype.unbindAllTextures = function () {
  16591. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16592. this._activeChannel = channel;
  16593. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16594. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16595. if (this.webGLVersion > 1) {
  16596. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16597. }
  16598. }
  16599. };
  16600. /**
  16601. * Sets a texture to the according uniform.
  16602. * @param channel The texture channel
  16603. * @param uniform The uniform to set
  16604. * @param texture The texture to apply
  16605. */
  16606. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16607. if (channel < 0) {
  16608. return;
  16609. }
  16610. if (uniform) {
  16611. this._boundUniforms[channel] = uniform;
  16612. }
  16613. this._setTexture(channel, texture);
  16614. };
  16615. /**
  16616. * Sets a depth stencil texture from a render target to the according uniform.
  16617. * @param channel The texture channel
  16618. * @param uniform The uniform to set
  16619. * @param texture The render target texture containing the depth stencil texture to apply
  16620. */
  16621. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16622. if (channel < 0) {
  16623. return;
  16624. }
  16625. if (uniform) {
  16626. this._boundUniforms[channel] = uniform;
  16627. }
  16628. if (!texture || !texture.depthStencilTexture) {
  16629. this._setTexture(channel, null);
  16630. }
  16631. else {
  16632. this._setTexture(channel, texture, false, true);
  16633. }
  16634. };
  16635. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16636. var uniform = this._boundUniforms[sourceSlot];
  16637. if (uniform._currentState === destination) {
  16638. return;
  16639. }
  16640. this._gl.uniform1i(uniform, destination);
  16641. uniform._currentState = destination;
  16642. };
  16643. Engine.prototype._getTextureWrapMode = function (mode) {
  16644. switch (mode) {
  16645. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16646. return this._gl.REPEAT;
  16647. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16648. return this._gl.CLAMP_TO_EDGE;
  16649. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16650. return this._gl.MIRRORED_REPEAT;
  16651. }
  16652. return this._gl.REPEAT;
  16653. };
  16654. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16655. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16656. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16657. // Not ready?
  16658. if (!texture) {
  16659. if (this._boundTexturesCache[channel] != null) {
  16660. this._activeChannel = channel;
  16661. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16662. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16663. if (this.webGLVersion > 1) {
  16664. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16665. }
  16666. }
  16667. return false;
  16668. }
  16669. // Video
  16670. if (texture.video) {
  16671. this._activeChannel = channel;
  16672. texture.update();
  16673. }
  16674. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16675. texture.delayLoad();
  16676. return false;
  16677. }
  16678. var internalTexture;
  16679. if (depthStencilTexture) {
  16680. internalTexture = texture.depthStencilTexture;
  16681. }
  16682. else if (texture.isReady()) {
  16683. internalTexture = texture.getInternalTexture();
  16684. }
  16685. else if (texture.isCube) {
  16686. internalTexture = this.emptyCubeTexture;
  16687. }
  16688. else if (texture.is3D) {
  16689. internalTexture = this.emptyTexture3D;
  16690. }
  16691. else {
  16692. internalTexture = this.emptyTexture;
  16693. }
  16694. if (!isPartOfTextureArray) {
  16695. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16696. }
  16697. var needToBind = true;
  16698. if (this._boundTexturesCache[channel] === internalTexture) {
  16699. this._moveBoundTextureOnTop(internalTexture);
  16700. if (!isPartOfTextureArray) {
  16701. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16702. }
  16703. needToBind = false;
  16704. }
  16705. this._activeChannel = channel;
  16706. if (internalTexture && internalTexture.is3D) {
  16707. if (needToBind) {
  16708. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16709. }
  16710. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16711. internalTexture._cachedWrapU = texture.wrapU;
  16712. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16713. }
  16714. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16715. internalTexture._cachedWrapV = texture.wrapV;
  16716. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16717. }
  16718. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16719. internalTexture._cachedWrapR = texture.wrapR;
  16720. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16721. }
  16722. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16723. }
  16724. else if (internalTexture && internalTexture.isCube) {
  16725. if (needToBind) {
  16726. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16727. }
  16728. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16729. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16730. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16731. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16732. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16733. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16734. }
  16735. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16736. }
  16737. else {
  16738. if (needToBind) {
  16739. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16740. }
  16741. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16742. internalTexture._cachedWrapU = texture.wrapU;
  16743. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16744. }
  16745. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16746. internalTexture._cachedWrapV = texture.wrapV;
  16747. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16748. }
  16749. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16750. }
  16751. return true;
  16752. };
  16753. /**
  16754. * Sets an array of texture to the webGL context
  16755. * @param channel defines the channel where the texture array must be set
  16756. * @param uniform defines the associated uniform location
  16757. * @param textures defines the array of textures to bind
  16758. */
  16759. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16760. if (channel < 0 || !uniform) {
  16761. return;
  16762. }
  16763. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16764. this._textureUnits = new Int32Array(textures.length);
  16765. }
  16766. for (var i = 0; i < textures.length; i++) {
  16767. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16768. }
  16769. this._gl.uniform1iv(uniform, this._textureUnits);
  16770. for (var index = 0; index < textures.length; index++) {
  16771. this._setTexture(this._textureUnits[index], textures[index], true);
  16772. }
  16773. };
  16774. /** @hidden */
  16775. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16776. var internalTexture = texture.getInternalTexture();
  16777. if (!internalTexture) {
  16778. return;
  16779. }
  16780. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16781. var value = texture.anisotropicFilteringLevel;
  16782. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16783. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16784. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16785. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16786. }
  16787. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16788. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16789. internalTexture._cachedAnisotropicFilteringLevel = value;
  16790. }
  16791. };
  16792. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16793. this._bindTextureDirectly(target, texture, true, true);
  16794. this._gl.texParameterf(target, parameter, value);
  16795. };
  16796. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16797. if (texture) {
  16798. this._bindTextureDirectly(target, texture, true, true);
  16799. }
  16800. this._gl.texParameteri(target, parameter, value);
  16801. };
  16802. /**
  16803. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16804. * @param x defines the x coordinate of the rectangle where pixels must be read
  16805. * @param y defines the y coordinate of the rectangle where pixels must be read
  16806. * @param width defines the width of the rectangle where pixels must be read
  16807. * @param height defines the height of the rectangle where pixels must be read
  16808. * @returns a Uint8Array containing RGBA colors
  16809. */
  16810. Engine.prototype.readPixels = function (x, y, width, height) {
  16811. var data = new Uint8Array(height * width * 4);
  16812. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16813. return data;
  16814. };
  16815. /**
  16816. * Add an externaly attached data from its key.
  16817. * This method call will fail and return false, if such key already exists.
  16818. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16819. * @param key the unique key that identifies the data
  16820. * @param data the data object to associate to the key for this Engine instance
  16821. * @return true if no such key were already present and the data was added successfully, false otherwise
  16822. */
  16823. Engine.prototype.addExternalData = function (key, data) {
  16824. if (!this._externalData) {
  16825. this._externalData = new BABYLON.StringDictionary();
  16826. }
  16827. return this._externalData.add(key, data);
  16828. };
  16829. /**
  16830. * Get an externaly attached data from its key
  16831. * @param key the unique key that identifies the data
  16832. * @return the associated data, if present (can be null), or undefined if not present
  16833. */
  16834. Engine.prototype.getExternalData = function (key) {
  16835. if (!this._externalData) {
  16836. this._externalData = new BABYLON.StringDictionary();
  16837. }
  16838. return this._externalData.get(key);
  16839. };
  16840. /**
  16841. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16842. * @param key the unique key that identifies the data
  16843. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16844. * @return the associated data, can be null if the factory returned null.
  16845. */
  16846. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16847. if (!this._externalData) {
  16848. this._externalData = new BABYLON.StringDictionary();
  16849. }
  16850. return this._externalData.getOrAddWithFactory(key, factory);
  16851. };
  16852. /**
  16853. * Remove an externaly attached data from the Engine instance
  16854. * @param key the unique key that identifies the data
  16855. * @return true if the data was successfully removed, false if it doesn't exist
  16856. */
  16857. Engine.prototype.removeExternalData = function (key) {
  16858. if (!this._externalData) {
  16859. this._externalData = new BABYLON.StringDictionary();
  16860. }
  16861. return this._externalData.remove(key);
  16862. };
  16863. /**
  16864. * Unbind all vertex attributes from the webGL context
  16865. */
  16866. Engine.prototype.unbindAllAttributes = function () {
  16867. if (this._mustWipeVertexAttributes) {
  16868. this._mustWipeVertexAttributes = false;
  16869. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16870. this._gl.disableVertexAttribArray(i);
  16871. this._vertexAttribArraysEnabled[i] = false;
  16872. this._currentBufferPointers[i].active = false;
  16873. }
  16874. return;
  16875. }
  16876. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16877. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16878. continue;
  16879. }
  16880. this._gl.disableVertexAttribArray(i);
  16881. this._vertexAttribArraysEnabled[i] = false;
  16882. this._currentBufferPointers[i].active = false;
  16883. }
  16884. };
  16885. /**
  16886. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16887. */
  16888. Engine.prototype.releaseEffects = function () {
  16889. for (var name in this._compiledEffects) {
  16890. this._deleteProgram(this._compiledEffects[name]._program);
  16891. }
  16892. this._compiledEffects = {};
  16893. };
  16894. /**
  16895. * Dispose and release all associated resources
  16896. */
  16897. Engine.prototype.dispose = function () {
  16898. this.hideLoadingUI();
  16899. this.stopRenderLoop();
  16900. // Release postProcesses
  16901. while (this.postProcesses.length) {
  16902. this.postProcesses[0].dispose();
  16903. }
  16904. // Empty texture
  16905. if (this._emptyTexture) {
  16906. this._releaseTexture(this._emptyTexture);
  16907. this._emptyTexture = null;
  16908. }
  16909. if (this._emptyCubeTexture) {
  16910. this._releaseTexture(this._emptyCubeTexture);
  16911. this._emptyCubeTexture = null;
  16912. }
  16913. // Rescale PP
  16914. if (this._rescalePostProcess) {
  16915. this._rescalePostProcess.dispose();
  16916. }
  16917. // Release scenes
  16918. while (this.scenes.length) {
  16919. this.scenes[0].dispose();
  16920. }
  16921. // Release audio engine
  16922. if (Engine.audioEngine) {
  16923. Engine.audioEngine.dispose();
  16924. }
  16925. // Release effects
  16926. this.releaseEffects();
  16927. // Unbind
  16928. this.unbindAllAttributes();
  16929. this._boundUniforms = [];
  16930. if (this._dummyFramebuffer) {
  16931. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16932. }
  16933. //WebVR
  16934. this.disableVR();
  16935. // Events
  16936. if (BABYLON.Tools.IsWindowObjectExist()) {
  16937. window.removeEventListener("blur", this._onBlur);
  16938. window.removeEventListener("focus", this._onFocus);
  16939. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16940. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16941. if (this._renderingCanvas) {
  16942. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16943. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16944. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16945. if (!this._doNotHandleContextLost) {
  16946. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16947. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16948. }
  16949. }
  16950. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16951. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16952. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16953. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16954. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16955. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16956. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16957. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16958. if (this._onVrDisplayConnect) {
  16959. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16960. if (this._onVrDisplayDisconnect) {
  16961. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16962. }
  16963. if (this._onVrDisplayPresentChange) {
  16964. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16965. }
  16966. this._onVrDisplayConnect = null;
  16967. this._onVrDisplayDisconnect = null;
  16968. }
  16969. }
  16970. // Remove from Instances
  16971. var index = Engine.Instances.indexOf(this);
  16972. if (index >= 0) {
  16973. Engine.Instances.splice(index, 1);
  16974. }
  16975. this._workingCanvas = null;
  16976. this._workingContext = null;
  16977. this._currentBufferPointers = [];
  16978. this._renderingCanvas = null;
  16979. this._currentProgram = null;
  16980. this._bindedRenderFunction = null;
  16981. this.onResizeObservable.clear();
  16982. this.onCanvasBlurObservable.clear();
  16983. this.onCanvasFocusObservable.clear();
  16984. this.onCanvasPointerOutObservable.clear();
  16985. this.onBeginFrameObservable.clear();
  16986. this.onEndFrameObservable.clear();
  16987. BABYLON.Effect.ResetCache();
  16988. // Abort active requests
  16989. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16990. var request = _a[_i];
  16991. request.abort();
  16992. }
  16993. };
  16994. // Loading screen
  16995. /**
  16996. * Display the loading screen
  16997. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16998. */
  16999. Engine.prototype.displayLoadingUI = function () {
  17000. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17001. return;
  17002. }
  17003. var loadingScreen = this.loadingScreen;
  17004. if (loadingScreen) {
  17005. loadingScreen.displayLoadingUI();
  17006. }
  17007. };
  17008. /**
  17009. * Hide the loading screen
  17010. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17011. */
  17012. Engine.prototype.hideLoadingUI = function () {
  17013. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17014. return;
  17015. }
  17016. var loadingScreen = this.loadingScreen;
  17017. if (loadingScreen) {
  17018. loadingScreen.hideLoadingUI();
  17019. }
  17020. };
  17021. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17022. /**
  17023. * Gets the current loading screen object
  17024. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17025. */
  17026. get: function () {
  17027. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17028. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17029. return this._loadingScreen;
  17030. },
  17031. /**
  17032. * Sets the current loading screen object
  17033. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17034. */
  17035. set: function (loadingScreen) {
  17036. this._loadingScreen = loadingScreen;
  17037. },
  17038. enumerable: true,
  17039. configurable: true
  17040. });
  17041. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17042. /**
  17043. * Sets the current loading screen text
  17044. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17045. */
  17046. set: function (text) {
  17047. this.loadingScreen.loadingUIText = text;
  17048. },
  17049. enumerable: true,
  17050. configurable: true
  17051. });
  17052. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17053. /**
  17054. * Sets the current loading screen background color
  17055. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17056. */
  17057. set: function (color) {
  17058. this.loadingScreen.loadingUIBackgroundColor = color;
  17059. },
  17060. enumerable: true,
  17061. configurable: true
  17062. });
  17063. /**
  17064. * Attach a new callback raised when context lost event is fired
  17065. * @param callback defines the callback to call
  17066. */
  17067. Engine.prototype.attachContextLostEvent = function (callback) {
  17068. if (this._renderingCanvas) {
  17069. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17070. }
  17071. };
  17072. /**
  17073. * Attach a new callback raised when context restored event is fired
  17074. * @param callback defines the callback to call
  17075. */
  17076. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17077. if (this._renderingCanvas) {
  17078. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17079. }
  17080. };
  17081. /**
  17082. * Gets the source code of the vertex shader associated with a specific webGL program
  17083. * @param program defines the program to use
  17084. * @returns a string containing the source code of the vertex shader associated with the program
  17085. */
  17086. Engine.prototype.getVertexShaderSource = function (program) {
  17087. var shaders = this._gl.getAttachedShaders(program);
  17088. if (!shaders) {
  17089. return null;
  17090. }
  17091. return this._gl.getShaderSource(shaders[0]);
  17092. };
  17093. /**
  17094. * Gets the source code of the fragment shader associated with a specific webGL program
  17095. * @param program defines the program to use
  17096. * @returns a string containing the source code of the fragment shader associated with the program
  17097. */
  17098. Engine.prototype.getFragmentShaderSource = function (program) {
  17099. var shaders = this._gl.getAttachedShaders(program);
  17100. if (!shaders) {
  17101. return null;
  17102. }
  17103. return this._gl.getShaderSource(shaders[1]);
  17104. };
  17105. /**
  17106. * Get the current error code of the webGL context
  17107. * @returns the error code
  17108. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17109. */
  17110. Engine.prototype.getError = function () {
  17111. return this._gl.getError();
  17112. };
  17113. // FPS
  17114. /**
  17115. * Gets the current framerate
  17116. * @returns a number representing the framerate
  17117. */
  17118. Engine.prototype.getFps = function () {
  17119. return this._fps;
  17120. };
  17121. /**
  17122. * Gets the time spent between current and previous frame
  17123. * @returns a number representing the delta time in ms
  17124. */
  17125. Engine.prototype.getDeltaTime = function () {
  17126. return this._deltaTime;
  17127. };
  17128. Engine.prototype._measureFps = function () {
  17129. this._performanceMonitor.sampleFrame();
  17130. this._fps = this._performanceMonitor.averageFPS;
  17131. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17132. };
  17133. /** @hidden */
  17134. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17135. if (faceIndex === void 0) { faceIndex = -1; }
  17136. if (level === void 0) { level = 0; }
  17137. var gl = this._gl;
  17138. if (!this._dummyFramebuffer) {
  17139. var dummy = gl.createFramebuffer();
  17140. if (!dummy) {
  17141. throw new Error("Unable to create dummy framebuffer");
  17142. }
  17143. this._dummyFramebuffer = dummy;
  17144. }
  17145. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17146. if (faceIndex > -1) {
  17147. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17148. }
  17149. else {
  17150. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17151. }
  17152. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17153. var buffer;
  17154. switch (readType) {
  17155. case gl.UNSIGNED_BYTE:
  17156. buffer = new Uint8Array(4 * width * height);
  17157. readType = gl.UNSIGNED_BYTE;
  17158. break;
  17159. default:
  17160. buffer = new Float32Array(4 * width * height);
  17161. readType = gl.FLOAT;
  17162. break;
  17163. }
  17164. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17165. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17166. return buffer;
  17167. };
  17168. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17169. if (this._webGLVersion > 1) {
  17170. return this._caps.colorBufferFloat;
  17171. }
  17172. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17173. };
  17174. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17175. if (this._webGLVersion > 1) {
  17176. return this._caps.colorBufferFloat;
  17177. }
  17178. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17179. };
  17180. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17181. Engine.prototype._canRenderToFramebuffer = function (type) {
  17182. var gl = this._gl;
  17183. //clear existing errors
  17184. while (gl.getError() !== gl.NO_ERROR) { }
  17185. var successful = true;
  17186. var texture = gl.createTexture();
  17187. gl.bindTexture(gl.TEXTURE_2D, texture);
  17188. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17191. var fb = gl.createFramebuffer();
  17192. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17193. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17194. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17195. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17196. successful = successful && (gl.getError() === gl.NO_ERROR);
  17197. //try render by clearing frame buffer's color buffer
  17198. if (successful) {
  17199. gl.clear(gl.COLOR_BUFFER_BIT);
  17200. successful = successful && (gl.getError() === gl.NO_ERROR);
  17201. }
  17202. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17203. if (successful) {
  17204. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17205. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17206. var readFormat = gl.RGBA;
  17207. var readType = gl.UNSIGNED_BYTE;
  17208. var buffer = new Uint8Array(4);
  17209. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17210. successful = successful && (gl.getError() === gl.NO_ERROR);
  17211. }
  17212. //clean up
  17213. gl.deleteTexture(texture);
  17214. gl.deleteFramebuffer(fb);
  17215. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17216. //clear accumulated errors
  17217. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17218. return successful;
  17219. };
  17220. /** @hidden */
  17221. Engine.prototype._getWebGLTextureType = function (type) {
  17222. if (type === Engine.TEXTURETYPE_FLOAT) {
  17223. return this._gl.FLOAT;
  17224. }
  17225. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17226. // Add Half Float Constant.
  17227. return this._gl.HALF_FLOAT_OES;
  17228. }
  17229. return this._gl.UNSIGNED_BYTE;
  17230. };
  17231. ;
  17232. Engine.prototype._getInternalFormat = function (format) {
  17233. var internalFormat = this._gl.RGBA;
  17234. switch (format) {
  17235. case Engine.TEXTUREFORMAT_ALPHA:
  17236. internalFormat = this._gl.ALPHA;
  17237. break;
  17238. case Engine.TEXTUREFORMAT_LUMINANCE:
  17239. internalFormat = this._gl.LUMINANCE;
  17240. break;
  17241. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17242. internalFormat = this._gl.LUMINANCE_ALPHA;
  17243. break;
  17244. case Engine.TEXTUREFORMAT_RGB:
  17245. internalFormat = this._gl.RGB;
  17246. break;
  17247. case Engine.TEXTUREFORMAT_RGBA:
  17248. internalFormat = this._gl.RGBA;
  17249. break;
  17250. case Engine.TEXTUREFORMAT_R:
  17251. internalFormat = this._gl.RED;
  17252. break;
  17253. case Engine.TEXTUREFORMAT_RG:
  17254. internalFormat = this._gl.RG;
  17255. break;
  17256. }
  17257. return internalFormat;
  17258. };
  17259. /** @hidden */
  17260. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17261. if (this._webGLVersion === 1) {
  17262. if (format !== undefined) {
  17263. switch (format) {
  17264. case Engine.TEXTUREFORMAT_LUMINANCE:
  17265. return this._gl.LUMINANCE;
  17266. case Engine.TEXTUREFORMAT_ALPHA:
  17267. return this._gl.ALPHA;
  17268. }
  17269. }
  17270. return this._gl.RGBA;
  17271. }
  17272. if (type === Engine.TEXTURETYPE_FLOAT) {
  17273. if (format !== undefined) {
  17274. switch (format) {
  17275. case Engine.TEXTUREFORMAT_R:
  17276. return this._gl.R32F;
  17277. case Engine.TEXTUREFORMAT_RG:
  17278. return this._gl.RG32F;
  17279. case Engine.TEXTUREFORMAT_RGB:
  17280. return this._gl.RGB32F;
  17281. }
  17282. }
  17283. return this._gl.RGBA32F;
  17284. }
  17285. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17286. if (format) {
  17287. switch (format) {
  17288. case Engine.TEXTUREFORMAT_R:
  17289. return this._gl.R16F;
  17290. case Engine.TEXTUREFORMAT_RG:
  17291. return this._gl.RG16F;
  17292. case Engine.TEXTUREFORMAT_RGB:
  17293. return this._gl.RGB16F;
  17294. }
  17295. }
  17296. return this._gl.RGBA16F;
  17297. }
  17298. if (format !== undefined) {
  17299. switch (format) {
  17300. case Engine.TEXTUREFORMAT_LUMINANCE:
  17301. return this._gl.LUMINANCE;
  17302. case Engine.TEXTUREFORMAT_RGB:
  17303. return this._gl.RGB;
  17304. case Engine.TEXTUREFORMAT_R:
  17305. return this._gl.R8;
  17306. case Engine.TEXTUREFORMAT_RG:
  17307. return this._gl.RG8;
  17308. case Engine.TEXTUREFORMAT_ALPHA:
  17309. return this._gl.ALPHA;
  17310. }
  17311. }
  17312. return this._gl.RGBA;
  17313. };
  17314. ;
  17315. /** @hidden */
  17316. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17317. if (type === Engine.TEXTURETYPE_FLOAT) {
  17318. return this._gl.RGBA32F;
  17319. }
  17320. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17321. return this._gl.RGBA16F;
  17322. }
  17323. return this._gl.RGBA8;
  17324. };
  17325. ;
  17326. /**
  17327. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17328. * @return the new query
  17329. */
  17330. Engine.prototype.createQuery = function () {
  17331. return this._gl.createQuery();
  17332. };
  17333. /**
  17334. * Delete and release a webGL query
  17335. * @param query defines the query to delete
  17336. * @return the current engine
  17337. */
  17338. Engine.prototype.deleteQuery = function (query) {
  17339. this._gl.deleteQuery(query);
  17340. return this;
  17341. };
  17342. /**
  17343. * Check if a given query has resolved and got its value
  17344. * @param query defines the query to check
  17345. * @returns true if the query got its value
  17346. */
  17347. Engine.prototype.isQueryResultAvailable = function (query) {
  17348. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17349. };
  17350. /**
  17351. * Gets the value of a given query
  17352. * @param query defines the query to check
  17353. * @returns the value of the query
  17354. */
  17355. Engine.prototype.getQueryResult = function (query) {
  17356. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17357. };
  17358. /**
  17359. * Initiates an occlusion query
  17360. * @param algorithmType defines the algorithm to use
  17361. * @param query defines the query to use
  17362. * @returns the current engine
  17363. * @see http://doc.babylonjs.com/features/occlusionquery
  17364. */
  17365. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17366. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17367. this._gl.beginQuery(glAlgorithm, query);
  17368. return this;
  17369. };
  17370. /**
  17371. * Ends an occlusion query
  17372. * @see http://doc.babylonjs.com/features/occlusionquery
  17373. * @param algorithmType defines the algorithm to use
  17374. * @returns the current engine
  17375. */
  17376. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17377. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17378. this._gl.endQuery(glAlgorithm);
  17379. return this;
  17380. };
  17381. /* Time queries */
  17382. Engine.prototype._createTimeQuery = function () {
  17383. var timerQuery = this._caps.timerQuery;
  17384. if (timerQuery.createQueryEXT) {
  17385. return timerQuery.createQueryEXT();
  17386. }
  17387. return this.createQuery();
  17388. };
  17389. Engine.prototype._deleteTimeQuery = function (query) {
  17390. var timerQuery = this._caps.timerQuery;
  17391. if (timerQuery.deleteQueryEXT) {
  17392. timerQuery.deleteQueryEXT(query);
  17393. return;
  17394. }
  17395. this.deleteQuery(query);
  17396. };
  17397. Engine.prototype._getTimeQueryResult = function (query) {
  17398. var timerQuery = this._caps.timerQuery;
  17399. if (timerQuery.getQueryObjectEXT) {
  17400. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17401. }
  17402. return this.getQueryResult(query);
  17403. };
  17404. Engine.prototype._getTimeQueryAvailability = function (query) {
  17405. var timerQuery = this._caps.timerQuery;
  17406. if (timerQuery.getQueryObjectEXT) {
  17407. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17408. }
  17409. return this.isQueryResultAvailable(query);
  17410. };
  17411. /**
  17412. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17413. * Please note that only one query can be issued at a time
  17414. * @returns a time token used to track the time span
  17415. */
  17416. Engine.prototype.startTimeQuery = function () {
  17417. var timerQuery = this._caps.timerQuery;
  17418. if (!timerQuery) {
  17419. return null;
  17420. }
  17421. var token = new BABYLON._TimeToken();
  17422. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17423. if (this._caps.canUseTimestampForTimerQuery) {
  17424. token._startTimeQuery = this._createTimeQuery();
  17425. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17426. }
  17427. else {
  17428. if (this._currentNonTimestampToken) {
  17429. return this._currentNonTimestampToken;
  17430. }
  17431. token._timeElapsedQuery = this._createTimeQuery();
  17432. if (timerQuery.beginQueryEXT) {
  17433. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17434. }
  17435. else {
  17436. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17437. }
  17438. this._currentNonTimestampToken = token;
  17439. }
  17440. return token;
  17441. };
  17442. /**
  17443. * Ends a time query
  17444. * @param token defines the token used to measure the time span
  17445. * @returns the time spent (in ns)
  17446. */
  17447. Engine.prototype.endTimeQuery = function (token) {
  17448. var timerQuery = this._caps.timerQuery;
  17449. if (!timerQuery || !token) {
  17450. return -1;
  17451. }
  17452. if (this._caps.canUseTimestampForTimerQuery) {
  17453. if (!token._startTimeQuery) {
  17454. return -1;
  17455. }
  17456. if (!token._endTimeQuery) {
  17457. token._endTimeQuery = this._createTimeQuery();
  17458. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17459. }
  17460. }
  17461. else if (!token._timeElapsedQueryEnded) {
  17462. if (!token._timeElapsedQuery) {
  17463. return -1;
  17464. }
  17465. if (timerQuery.endQueryEXT) {
  17466. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17467. }
  17468. else {
  17469. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17470. }
  17471. token._timeElapsedQueryEnded = true;
  17472. }
  17473. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17474. var available = false;
  17475. if (token._endTimeQuery) {
  17476. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17477. }
  17478. else if (token._timeElapsedQuery) {
  17479. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17480. }
  17481. if (available && !disjoint) {
  17482. var result = 0;
  17483. if (this._caps.canUseTimestampForTimerQuery) {
  17484. if (!token._startTimeQuery || !token._endTimeQuery) {
  17485. return -1;
  17486. }
  17487. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17488. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17489. result = timeEnd - timeStart;
  17490. this._deleteTimeQuery(token._startTimeQuery);
  17491. this._deleteTimeQuery(token._endTimeQuery);
  17492. token._startTimeQuery = null;
  17493. token._endTimeQuery = null;
  17494. }
  17495. else {
  17496. if (!token._timeElapsedQuery) {
  17497. return -1;
  17498. }
  17499. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17500. this._deleteTimeQuery(token._timeElapsedQuery);
  17501. token._timeElapsedQuery = null;
  17502. token._timeElapsedQueryEnded = false;
  17503. this._currentNonTimestampToken = null;
  17504. }
  17505. return result;
  17506. }
  17507. return -1;
  17508. };
  17509. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17510. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17511. };
  17512. // Transform feedback
  17513. /**
  17514. * Creates a webGL transform feedback object
  17515. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17516. * @returns the webGL transform feedback object
  17517. */
  17518. Engine.prototype.createTransformFeedback = function () {
  17519. return this._gl.createTransformFeedback();
  17520. };
  17521. /**
  17522. * Delete a webGL transform feedback object
  17523. * @param value defines the webGL transform feedback object to delete
  17524. */
  17525. Engine.prototype.deleteTransformFeedback = function (value) {
  17526. this._gl.deleteTransformFeedback(value);
  17527. };
  17528. /**
  17529. * Bind a webGL transform feedback object to the webgl context
  17530. * @param value defines the webGL transform feedback object to bind
  17531. */
  17532. Engine.prototype.bindTransformFeedback = function (value) {
  17533. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17534. };
  17535. /**
  17536. * Begins a transform feedback operation
  17537. * @param usePoints defines if points or triangles must be used
  17538. */
  17539. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17540. if (usePoints === void 0) { usePoints = true; }
  17541. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17542. };
  17543. /**
  17544. * Ends a transform feedback operation
  17545. */
  17546. Engine.prototype.endTransformFeedback = function () {
  17547. this._gl.endTransformFeedback();
  17548. };
  17549. /**
  17550. * Specify the varyings to use with transform feedback
  17551. * @param program defines the associated webGL program
  17552. * @param value defines the list of strings representing the varying names
  17553. */
  17554. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17555. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17556. };
  17557. /**
  17558. * Bind a webGL buffer for a transform feedback operation
  17559. * @param value defines the webGL buffer to bind
  17560. */
  17561. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17562. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17563. };
  17564. /** @hidden */
  17565. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17566. var _this = this;
  17567. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17568. this._activeRequests.push(request);
  17569. request.onCompleteObservable.add(function (request) {
  17570. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17571. });
  17572. return request;
  17573. };
  17574. /** @hidden */
  17575. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17576. var _this = this;
  17577. return new Promise(function (resolve, reject) {
  17578. _this._loadFile(url, function (data) {
  17579. resolve(data);
  17580. }, undefined, database, useArrayBuffer, function (request, exception) {
  17581. reject(exception);
  17582. });
  17583. });
  17584. };
  17585. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17586. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17587. var onload = function (data) {
  17588. loadedFiles[index] = data;
  17589. loadedFiles._internalCount++;
  17590. if (loadedFiles._internalCount === 6) {
  17591. onfinish(loadedFiles);
  17592. }
  17593. };
  17594. var onerror = function (request, exception) {
  17595. if (onErrorCallBack && request) {
  17596. onErrorCallBack(request.status + " " + request.statusText, exception);
  17597. }
  17598. };
  17599. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17600. };
  17601. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17602. if (onError === void 0) { onError = null; }
  17603. var loadedFiles = [];
  17604. loadedFiles._internalCount = 0;
  17605. for (var index = 0; index < 6; index++) {
  17606. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17607. }
  17608. };
  17609. // Statics
  17610. /**
  17611. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17612. * @returns true if the engine can be created
  17613. * @ignorenaming
  17614. */
  17615. Engine.isSupported = function () {
  17616. try {
  17617. var tempcanvas = document.createElement("canvas");
  17618. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17619. return gl != null && !!window.WebGLRenderingContext;
  17620. }
  17621. catch (e) {
  17622. return false;
  17623. }
  17624. };
  17625. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17626. Engine.ExceptionList = [
  17627. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17628. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17629. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17630. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17631. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17632. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17633. ];
  17634. /** Gets the list of created engines */
  17635. Engine.Instances = new Array();
  17636. // Const statics
  17637. Engine._ALPHA_DISABLE = 0;
  17638. Engine._ALPHA_ADD = 1;
  17639. Engine._ALPHA_COMBINE = 2;
  17640. Engine._ALPHA_SUBTRACT = 3;
  17641. Engine._ALPHA_MULTIPLY = 4;
  17642. Engine._ALPHA_MAXIMIZED = 5;
  17643. Engine._ALPHA_ONEONE = 6;
  17644. Engine._ALPHA_PREMULTIPLIED = 7;
  17645. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17646. Engine._ALPHA_INTERPOLATE = 9;
  17647. Engine._ALPHA_SCREENMODE = 10;
  17648. Engine._DELAYLOADSTATE_NONE = 0;
  17649. Engine._DELAYLOADSTATE_LOADED = 1;
  17650. Engine._DELAYLOADSTATE_LOADING = 2;
  17651. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17652. Engine._TEXTUREFORMAT_ALPHA = 0;
  17653. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17654. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17655. Engine._TEXTUREFORMAT_RGB = 4;
  17656. Engine._TEXTUREFORMAT_RGBA = 5;
  17657. Engine._TEXTUREFORMAT_R = 6;
  17658. Engine._TEXTUREFORMAT_RG = 7;
  17659. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17660. Engine._TEXTURETYPE_FLOAT = 1;
  17661. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17662. // Depht or Stencil test Constants.
  17663. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17664. 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.
  17665. 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.
  17666. 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.
  17667. 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.
  17668. 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.
  17669. 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.
  17670. 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.
  17671. // Stencil Actions Constants.
  17672. Engine._KEEP = 0x1E00;
  17673. Engine._REPLACE = 0x1E01;
  17674. Engine._INCR = 0x1E02;
  17675. Engine._DECR = 0x1E03;
  17676. Engine._INVERT = 0x150A;
  17677. Engine._INCR_WRAP = 0x8507;
  17678. Engine._DECR_WRAP = 0x8508;
  17679. // Texture rescaling mode
  17680. Engine._SCALEMODE_FLOOR = 1;
  17681. Engine._SCALEMODE_NEAREST = 2;
  17682. Engine._SCALEMODE_CEILING = 3;
  17683. // Updatable statics so stick with vars here
  17684. /**
  17685. * Gets or sets the epsilon value used by collision engine
  17686. */
  17687. Engine.CollisionsEpsilon = 0.001;
  17688. /**
  17689. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17690. */
  17691. Engine.CodeRepository = "src/";
  17692. /**
  17693. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17694. */
  17695. Engine.ShadersRepository = "src/Shaders/";
  17696. return Engine;
  17697. }());
  17698. BABYLON.Engine = Engine;
  17699. })(BABYLON || (BABYLON = {}));
  17700. //# sourceMappingURL=babylon.engine.js.map
  17701. var BABYLON;
  17702. (function (BABYLON) {
  17703. /**
  17704. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17705. */
  17706. var Node = /** @class */ (function () {
  17707. /**
  17708. * Creates a new Node
  17709. * @param {string} name - the name and id to be given to this node
  17710. * @param {BABYLON.Scene} the scene this node will be added to
  17711. */
  17712. function Node(name, scene) {
  17713. if (scene === void 0) { scene = null; }
  17714. /**
  17715. * Gets or sets a string used to store user defined state for the node
  17716. */
  17717. this.state = "";
  17718. /**
  17719. * Gets or sets an object used to store user defined information for the node
  17720. */
  17721. this.metadata = null;
  17722. /**
  17723. * Gets or sets a boolean used to define if the node must be serialized
  17724. */
  17725. this.doNotSerialize = false;
  17726. /** @hidden */
  17727. this._isDisposed = false;
  17728. /**
  17729. * Gets a list of Animations associated with the node
  17730. */
  17731. this.animations = new Array();
  17732. this._ranges = {};
  17733. this._isEnabled = true;
  17734. this._isReady = true;
  17735. /** @hidden */
  17736. this._currentRenderId = -1;
  17737. this._parentRenderId = -1;
  17738. this._childRenderId = -1;
  17739. this._animationPropertiesOverride = null;
  17740. /**
  17741. * An event triggered when the mesh is disposed
  17742. */
  17743. this.onDisposeObservable = new BABYLON.Observable();
  17744. // Behaviors
  17745. this._behaviors = new Array();
  17746. this.name = name;
  17747. this.id = name;
  17748. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17749. this.uniqueId = this._scene.getUniqueId();
  17750. this._initCache();
  17751. }
  17752. /**
  17753. * Gets a boolean indicating if the node has been disposed
  17754. * @returns true if the node was disposed
  17755. */
  17756. Node.prototype.isDisposed = function () {
  17757. return this._isDisposed;
  17758. };
  17759. Object.defineProperty(Node.prototype, "parent", {
  17760. get: function () {
  17761. return this._parentNode;
  17762. },
  17763. /**
  17764. * Gets or sets the parent of the node
  17765. */
  17766. set: function (parent) {
  17767. if (this._parentNode === parent) {
  17768. return;
  17769. }
  17770. // Remove self from list of children of parent
  17771. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17772. var index = this._parentNode._children.indexOf(this);
  17773. if (index !== -1) {
  17774. this._parentNode._children.splice(index, 1);
  17775. }
  17776. }
  17777. // Store new parent
  17778. this._parentNode = parent;
  17779. // Add as child to new parent
  17780. if (this._parentNode) {
  17781. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17782. this._parentNode._children = new Array();
  17783. }
  17784. this._parentNode._children.push(this);
  17785. }
  17786. },
  17787. enumerable: true,
  17788. configurable: true
  17789. });
  17790. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17791. /**
  17792. * Gets or sets the animation properties override
  17793. */
  17794. get: function () {
  17795. if (!this._animationPropertiesOverride) {
  17796. return this._scene.animationPropertiesOverride;
  17797. }
  17798. return this._animationPropertiesOverride;
  17799. },
  17800. set: function (value) {
  17801. this._animationPropertiesOverride = value;
  17802. },
  17803. enumerable: true,
  17804. configurable: true
  17805. });
  17806. /**
  17807. * Gets a string idenfifying the name of the class
  17808. * @returns "Node" string
  17809. */
  17810. Node.prototype.getClassName = function () {
  17811. return "Node";
  17812. };
  17813. Object.defineProperty(Node.prototype, "onDispose", {
  17814. /**
  17815. * Sets a callback that will be raised when the node will be disposed
  17816. */
  17817. set: function (callback) {
  17818. if (this._onDisposeObserver) {
  17819. this.onDisposeObservable.remove(this._onDisposeObserver);
  17820. }
  17821. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17822. },
  17823. enumerable: true,
  17824. configurable: true
  17825. });
  17826. /**
  17827. * Gets the scene of the node
  17828. * @returns a {BABYLON.Scene}
  17829. */
  17830. Node.prototype.getScene = function () {
  17831. return this._scene;
  17832. };
  17833. /**
  17834. * Gets the engine of the node
  17835. * @returns a {BABYLON.Engine}
  17836. */
  17837. Node.prototype.getEngine = function () {
  17838. return this._scene.getEngine();
  17839. };
  17840. /**
  17841. * Attach a behavior to the node
  17842. * @see http://doc.babylonjs.com/features/behaviour
  17843. * @param behavior defines the behavior to attach
  17844. * @returns the current Node
  17845. */
  17846. Node.prototype.addBehavior = function (behavior) {
  17847. var _this = this;
  17848. var index = this._behaviors.indexOf(behavior);
  17849. if (index !== -1) {
  17850. return this;
  17851. }
  17852. behavior.init();
  17853. if (this._scene.isLoading) {
  17854. // We defer the attach when the scene will be loaded
  17855. this._scene.onDataLoadedObservable.addOnce(function () {
  17856. behavior.attach(_this);
  17857. });
  17858. }
  17859. else {
  17860. behavior.attach(this);
  17861. }
  17862. this._behaviors.push(behavior);
  17863. return this;
  17864. };
  17865. /**
  17866. * Remove an attached behavior
  17867. * @see http://doc.babylonjs.com/features/behaviour
  17868. * @param behavior defines the behavior to attach
  17869. * @returns the current Node
  17870. */
  17871. Node.prototype.removeBehavior = function (behavior) {
  17872. var index = this._behaviors.indexOf(behavior);
  17873. if (index === -1) {
  17874. return this;
  17875. }
  17876. this._behaviors[index].detach();
  17877. this._behaviors.splice(index, 1);
  17878. return this;
  17879. };
  17880. Object.defineProperty(Node.prototype, "behaviors", {
  17881. /**
  17882. * Gets the list of attached behaviors
  17883. * @see http://doc.babylonjs.com/features/behaviour
  17884. */
  17885. get: function () {
  17886. return this._behaviors;
  17887. },
  17888. enumerable: true,
  17889. configurable: true
  17890. });
  17891. /**
  17892. * Gets an attached behavior by name
  17893. * @param name defines the name of the behavior to look for
  17894. * @see http://doc.babylonjs.com/features/behaviour
  17895. * @returns null if behavior was not found else the requested behavior
  17896. */
  17897. Node.prototype.getBehaviorByName = function (name) {
  17898. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17899. var behavior = _a[_i];
  17900. if (behavior.name === name) {
  17901. return behavior;
  17902. }
  17903. }
  17904. return null;
  17905. };
  17906. /**
  17907. * Returns the world matrix of the node
  17908. * @returns a matrix containing the node's world matrix
  17909. */
  17910. Node.prototype.getWorldMatrix = function () {
  17911. return BABYLON.Matrix.Identity();
  17912. };
  17913. /** @hidden */
  17914. Node.prototype._getWorldMatrixDeterminant = function () {
  17915. return 1;
  17916. };
  17917. // override it in derived class if you add new variables to the cache
  17918. // and call the parent class method
  17919. /** @hidden */
  17920. Node.prototype._initCache = function () {
  17921. this._cache = {};
  17922. this._cache.parent = undefined;
  17923. };
  17924. /** @hidden */
  17925. Node.prototype.updateCache = function (force) {
  17926. if (!force && this.isSynchronized())
  17927. return;
  17928. this._cache.parent = this.parent;
  17929. this._updateCache();
  17930. };
  17931. // override it in derived class if you add new variables to the cache
  17932. // and call the parent class method if !ignoreParentClass
  17933. /** @hidden */
  17934. Node.prototype._updateCache = function (ignoreParentClass) {
  17935. };
  17936. // override it in derived class if you add new variables to the cache
  17937. /** @hidden */
  17938. Node.prototype._isSynchronized = function () {
  17939. return true;
  17940. };
  17941. /** @hidden */
  17942. Node.prototype._markSyncedWithParent = function () {
  17943. if (this.parent) {
  17944. this._parentRenderId = this.parent._childRenderId;
  17945. }
  17946. };
  17947. /** @hidden */
  17948. Node.prototype.isSynchronizedWithParent = function () {
  17949. if (!this.parent) {
  17950. return true;
  17951. }
  17952. if (this._parentRenderId !== this.parent._childRenderId) {
  17953. return false;
  17954. }
  17955. return this.parent.isSynchronized();
  17956. };
  17957. /** @hidden */
  17958. Node.prototype.isSynchronized = function (updateCache) {
  17959. var check = this.hasNewParent();
  17960. check = check || !this.isSynchronizedWithParent();
  17961. check = check || !this._isSynchronized();
  17962. if (updateCache)
  17963. this.updateCache(true);
  17964. return !check;
  17965. };
  17966. /** @hidden */
  17967. Node.prototype.hasNewParent = function (update) {
  17968. if (this._cache.parent === this.parent)
  17969. return false;
  17970. if (update)
  17971. this._cache.parent = this.parent;
  17972. return true;
  17973. };
  17974. /**
  17975. * Is this node ready to be used/rendered
  17976. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17977. * @return true if the node is ready
  17978. */
  17979. Node.prototype.isReady = function (completeCheck) {
  17980. if (completeCheck === void 0) { completeCheck = false; }
  17981. return this._isReady;
  17982. };
  17983. /**
  17984. * Is this node enabled?
  17985. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  17986. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  17987. * @return whether this node (and its parent) is enabled
  17988. */
  17989. Node.prototype.isEnabled = function (checkAncestors) {
  17990. if (checkAncestors === void 0) { checkAncestors = true; }
  17991. if (checkAncestors === false) {
  17992. return this._isEnabled;
  17993. }
  17994. if (this._isEnabled === false) {
  17995. return false;
  17996. }
  17997. if (this.parent !== undefined && this.parent !== null) {
  17998. return this.parent.isEnabled(checkAncestors);
  17999. }
  18000. return true;
  18001. };
  18002. /**
  18003. * Set the enabled state of this node
  18004. * @param value defines the new enabled state
  18005. */
  18006. Node.prototype.setEnabled = function (value) {
  18007. this._isEnabled = value;
  18008. };
  18009. /**
  18010. * Is this node a descendant of the given node?
  18011. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18012. * @param ancestor defines the parent node to inspect
  18013. * @returns a boolean indicating if this node is a descendant of the given node
  18014. */
  18015. Node.prototype.isDescendantOf = function (ancestor) {
  18016. if (this.parent) {
  18017. if (this.parent === ancestor) {
  18018. return true;
  18019. }
  18020. return this.parent.isDescendantOf(ancestor);
  18021. }
  18022. return false;
  18023. };
  18024. /** @hidden */
  18025. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18026. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18027. if (!this._children) {
  18028. return;
  18029. }
  18030. for (var index = 0; index < this._children.length; index++) {
  18031. var item = this._children[index];
  18032. if (!predicate || predicate(item)) {
  18033. results.push(item);
  18034. }
  18035. if (!directDescendantsOnly) {
  18036. item._getDescendants(results, false, predicate);
  18037. }
  18038. }
  18039. };
  18040. /**
  18041. * Will return all nodes that have this node as ascendant
  18042. * @param directDescendantsOnly defines 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
  18043. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  18044. * @return all children nodes of all types
  18045. */
  18046. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18047. var results = new Array();
  18048. this._getDescendants(results, directDescendantsOnly, predicate);
  18049. return results;
  18050. };
  18051. /**
  18052. * Get all child-meshes of this node
  18053. * @param directDescendantsOnly defines 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
  18054. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  18055. * @returns an array of {BABYLON.AbstractMesh}
  18056. */
  18057. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18058. var results = [];
  18059. this._getDescendants(results, directDescendantsOnly, function (node) {
  18060. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18061. });
  18062. return results;
  18063. };
  18064. /**
  18065. * Get all child-transformNodes of this node
  18066. * @param directDescendantsOnly defines 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
  18067. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  18068. * @returns an array of {BABYLON.TransformNode}
  18069. */
  18070. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18071. var results = [];
  18072. this._getDescendants(results, directDescendantsOnly, function (node) {
  18073. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18074. });
  18075. return results;
  18076. };
  18077. /**
  18078. * Get all direct children of this node
  18079. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  18080. * @returns an array of {BABYLON.Node}
  18081. */
  18082. Node.prototype.getChildren = function (predicate) {
  18083. return this.getDescendants(true, predicate);
  18084. };
  18085. /** @hidden */
  18086. Node.prototype._setReady = function (state) {
  18087. if (state === this._isReady) {
  18088. return;
  18089. }
  18090. if (!state) {
  18091. this._isReady = false;
  18092. return;
  18093. }
  18094. if (this.onReady) {
  18095. this.onReady(this);
  18096. }
  18097. this._isReady = true;
  18098. };
  18099. /**
  18100. * Get an animation by name
  18101. * @param name defines the name of the animation to look for
  18102. * @returns null if not found else the requested animation
  18103. */
  18104. Node.prototype.getAnimationByName = function (name) {
  18105. for (var i = 0; i < this.animations.length; i++) {
  18106. var animation = this.animations[i];
  18107. if (animation.name === name) {
  18108. return animation;
  18109. }
  18110. }
  18111. return null;
  18112. };
  18113. /**
  18114. * Creates an animation range for this node
  18115. * @param name defines the name of the range
  18116. * @param from defines the starting key
  18117. * @param to defines the end key
  18118. */
  18119. Node.prototype.createAnimationRange = function (name, from, to) {
  18120. // check name not already in use
  18121. if (!this._ranges[name]) {
  18122. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18123. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18124. if (this.animations[i]) {
  18125. this.animations[i].createRange(name, from, to);
  18126. }
  18127. }
  18128. }
  18129. };
  18130. /**
  18131. * Delete a specific animation range
  18132. * @param name defines the name of the range to delete
  18133. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18134. */
  18135. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18136. if (deleteFrames === void 0) { deleteFrames = true; }
  18137. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18138. if (this.animations[i]) {
  18139. this.animations[i].deleteRange(name, deleteFrames);
  18140. }
  18141. }
  18142. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18143. };
  18144. /**
  18145. * Get an animation range by name
  18146. * @param name defines the name of the animation range to look for
  18147. * @returns null if not found else the requested animation range
  18148. */
  18149. Node.prototype.getAnimationRange = function (name) {
  18150. return this._ranges[name];
  18151. };
  18152. /**
  18153. * Will start the animation sequence
  18154. * @param name defines the range frames for animation sequence
  18155. * @param loop defines if the animation should loop (false by default)
  18156. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18157. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18158. * @returns the object created for this animation. If range does not exist, it will return null
  18159. */
  18160. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18161. var range = this.getAnimationRange(name);
  18162. if (!range) {
  18163. return null;
  18164. }
  18165. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18166. };
  18167. /**
  18168. * Serialize animation ranges into a JSON compatible object
  18169. * @returns serialization object
  18170. */
  18171. Node.prototype.serializeAnimationRanges = function () {
  18172. var serializationRanges = [];
  18173. for (var name in this._ranges) {
  18174. var localRange = this._ranges[name];
  18175. if (!localRange) {
  18176. continue;
  18177. }
  18178. var range = {};
  18179. range.name = name;
  18180. range.from = localRange.from;
  18181. range.to = localRange.to;
  18182. serializationRanges.push(range);
  18183. }
  18184. return serializationRanges;
  18185. };
  18186. /**
  18187. * Computes the world matrix of the node
  18188. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18189. * @returns the world matrix
  18190. */
  18191. Node.prototype.computeWorldMatrix = function (force) {
  18192. return BABYLON.Matrix.Identity();
  18193. };
  18194. /**
  18195. * Releases resources associated with this node.
  18196. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18197. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18198. */
  18199. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18200. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18201. if (!doNotRecurse) {
  18202. var nodes = this.getDescendants(true);
  18203. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18204. var node = nodes_1[_i];
  18205. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18206. }
  18207. }
  18208. else {
  18209. var transformNodes = this.getChildTransformNodes(true);
  18210. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18211. var transformNode = transformNodes_1[_a];
  18212. transformNode.parent = null;
  18213. transformNode.computeWorldMatrix(true);
  18214. }
  18215. }
  18216. this.parent = null;
  18217. // Callback
  18218. this.onDisposeObservable.notifyObservers(this);
  18219. this.onDisposeObservable.clear();
  18220. // Behaviors
  18221. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18222. var behavior = _c[_b];
  18223. behavior.detach();
  18224. }
  18225. this._behaviors = [];
  18226. this._isDisposed = true;
  18227. };
  18228. /**
  18229. * Parse animation range data from a serialization object and store them into a given node
  18230. * @param node defines where to store the animation ranges
  18231. * @param parsedNode defines the serialization object to read data from
  18232. * @param scene defines the hosting scene
  18233. */
  18234. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18235. if (parsedNode.ranges) {
  18236. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18237. var data = parsedNode.ranges[index];
  18238. node.createAnimationRange(data.name, data.from, data.to);
  18239. }
  18240. }
  18241. };
  18242. __decorate([
  18243. BABYLON.serialize()
  18244. ], Node.prototype, "name", void 0);
  18245. __decorate([
  18246. BABYLON.serialize()
  18247. ], Node.prototype, "id", void 0);
  18248. __decorate([
  18249. BABYLON.serialize()
  18250. ], Node.prototype, "uniqueId", void 0);
  18251. __decorate([
  18252. BABYLON.serialize()
  18253. ], Node.prototype, "state", void 0);
  18254. __decorate([
  18255. BABYLON.serialize()
  18256. ], Node.prototype, "metadata", void 0);
  18257. return Node;
  18258. }());
  18259. BABYLON.Node = Node;
  18260. })(BABYLON || (BABYLON = {}));
  18261. //# sourceMappingURL=babylon.node.js.map
  18262. var BABYLON;
  18263. (function (BABYLON) {
  18264. var BoundingSphere = /** @class */ (function () {
  18265. /**
  18266. * Creates a new bounding sphere
  18267. * @param min defines the minimum vector (in local space)
  18268. * @param max defines the maximum vector (in local space)
  18269. */
  18270. function BoundingSphere(min, max) {
  18271. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18272. this.reConstruct(min, max);
  18273. }
  18274. /**
  18275. * Recreates the entire bounding sphere from scratch
  18276. * @param min defines the new minimum vector (in local space)
  18277. * @param max defines the new maximum vector (in local space)
  18278. */
  18279. BoundingSphere.prototype.reConstruct = function (min, max) {
  18280. this.minimum = min.clone();
  18281. this.maximum = max.clone();
  18282. var distance = BABYLON.Vector3.Distance(min, max);
  18283. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18284. this.radius = distance * 0.5;
  18285. this.centerWorld = BABYLON.Vector3.Zero();
  18286. this._update(BABYLON.Matrix.Identity());
  18287. };
  18288. // Methods
  18289. BoundingSphere.prototype._update = function (world) {
  18290. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18291. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18292. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18293. };
  18294. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18295. for (var i = 0; i < 6; i++) {
  18296. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18297. return false;
  18298. }
  18299. return true;
  18300. };
  18301. BoundingSphere.prototype.intersectsPoint = function (point) {
  18302. var x = this.centerWorld.x - point.x;
  18303. var y = this.centerWorld.y - point.y;
  18304. var z = this.centerWorld.z - point.z;
  18305. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18306. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18307. return false;
  18308. return true;
  18309. };
  18310. // Statics
  18311. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18312. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18313. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18314. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18315. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18316. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18317. return false;
  18318. return true;
  18319. };
  18320. return BoundingSphere;
  18321. }());
  18322. BABYLON.BoundingSphere = BoundingSphere;
  18323. })(BABYLON || (BABYLON = {}));
  18324. //# sourceMappingURL=babylon.boundingSphere.js.map
  18325. var BABYLON;
  18326. (function (BABYLON) {
  18327. var BoundingBox = /** @class */ (function () {
  18328. /**
  18329. * Creates a new bounding box
  18330. * @param min defines the minimum vector (in local space)
  18331. * @param max defines the maximum vector (in local space)
  18332. */
  18333. function BoundingBox(min, max) {
  18334. this.vectorsWorld = new Array();
  18335. this.reConstruct(min, max);
  18336. }
  18337. // Methods
  18338. /**
  18339. * Recreates the entire bounding box from scratch
  18340. * @param min defines the new minimum vector (in local space)
  18341. * @param max defines the new maximum vector (in local space)
  18342. */
  18343. BoundingBox.prototype.reConstruct = function (min, max) {
  18344. this.minimum = min.clone();
  18345. this.maximum = max.clone();
  18346. // Bounding vectors
  18347. this.vectors = new Array();
  18348. this.vectors.push(this.minimum.clone());
  18349. this.vectors.push(this.maximum.clone());
  18350. this.vectors.push(this.minimum.clone());
  18351. this.vectors[2].x = this.maximum.x;
  18352. this.vectors.push(this.minimum.clone());
  18353. this.vectors[3].y = this.maximum.y;
  18354. this.vectors.push(this.minimum.clone());
  18355. this.vectors[4].z = this.maximum.z;
  18356. this.vectors.push(this.maximum.clone());
  18357. this.vectors[5].z = this.minimum.z;
  18358. this.vectors.push(this.maximum.clone());
  18359. this.vectors[6].x = this.minimum.x;
  18360. this.vectors.push(this.maximum.clone());
  18361. this.vectors[7].y = this.minimum.y;
  18362. // OBB
  18363. this.center = this.maximum.add(this.minimum).scale(0.5);
  18364. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18365. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18366. // World
  18367. for (var index = 0; index < this.vectors.length; index++) {
  18368. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18369. }
  18370. this.minimumWorld = BABYLON.Vector3.Zero();
  18371. this.maximumWorld = BABYLON.Vector3.Zero();
  18372. this.centerWorld = BABYLON.Vector3.Zero();
  18373. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18374. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18375. };
  18376. BoundingBox.prototype.getWorldMatrix = function () {
  18377. return this._worldMatrix;
  18378. };
  18379. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18380. this._worldMatrix.copyFrom(matrix);
  18381. return this;
  18382. };
  18383. BoundingBox.prototype._update = function (world) {
  18384. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18385. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18386. for (var index = 0; index < this.vectors.length; index++) {
  18387. var v = this.vectorsWorld[index];
  18388. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18389. if (v.x < this.minimumWorld.x)
  18390. this.minimumWorld.x = v.x;
  18391. if (v.y < this.minimumWorld.y)
  18392. this.minimumWorld.y = v.y;
  18393. if (v.z < this.minimumWorld.z)
  18394. this.minimumWorld.z = v.z;
  18395. if (v.x > this.maximumWorld.x)
  18396. this.maximumWorld.x = v.x;
  18397. if (v.y > this.maximumWorld.y)
  18398. this.maximumWorld.y = v.y;
  18399. if (v.z > this.maximumWorld.z)
  18400. this.maximumWorld.z = v.z;
  18401. }
  18402. // Extend
  18403. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18404. this.extendSizeWorld.scaleInPlace(0.5);
  18405. // OBB
  18406. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18407. this.centerWorld.scaleInPlace(0.5);
  18408. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18409. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18410. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18411. this._worldMatrix = world;
  18412. };
  18413. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18414. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18415. };
  18416. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18417. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18418. };
  18419. BoundingBox.prototype.intersectsPoint = function (point) {
  18420. var delta = -BABYLON.Epsilon;
  18421. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18422. return false;
  18423. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18424. return false;
  18425. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18426. return false;
  18427. return true;
  18428. };
  18429. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18430. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18431. };
  18432. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18433. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18434. return false;
  18435. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18436. return false;
  18437. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18438. return false;
  18439. return true;
  18440. };
  18441. // Statics
  18442. BoundingBox.Intersects = function (box0, box1) {
  18443. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18444. return false;
  18445. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18446. return false;
  18447. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18448. return false;
  18449. return true;
  18450. };
  18451. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18452. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18453. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18454. return (num <= (sphereRadius * sphereRadius));
  18455. };
  18456. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18457. for (var p = 0; p < 6; p++) {
  18458. for (var i = 0; i < 8; i++) {
  18459. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18460. return false;
  18461. }
  18462. }
  18463. }
  18464. return true;
  18465. };
  18466. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18467. for (var p = 0; p < 6; p++) {
  18468. var inCount = 8;
  18469. for (var i = 0; i < 8; i++) {
  18470. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18471. --inCount;
  18472. }
  18473. else {
  18474. break;
  18475. }
  18476. }
  18477. if (inCount === 0)
  18478. return false;
  18479. }
  18480. return true;
  18481. };
  18482. return BoundingBox;
  18483. }());
  18484. BABYLON.BoundingBox = BoundingBox;
  18485. })(BABYLON || (BABYLON = {}));
  18486. //# sourceMappingURL=babylon.boundingBox.js.map
  18487. var BABYLON;
  18488. (function (BABYLON) {
  18489. var computeBoxExtents = function (axis, box) {
  18490. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18491. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18492. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18493. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18494. var r = r0 + r1 + r2;
  18495. return {
  18496. min: p - r,
  18497. max: p + r
  18498. };
  18499. };
  18500. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18501. var axisOverlap = function (axis, box0, box1) {
  18502. var result0 = computeBoxExtents(axis, box0);
  18503. var result1 = computeBoxExtents(axis, box1);
  18504. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18505. };
  18506. var BoundingInfo = /** @class */ (function () {
  18507. function BoundingInfo(minimum, maximum) {
  18508. this.minimum = minimum;
  18509. this.maximum = maximum;
  18510. this._isLocked = false;
  18511. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18512. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18513. }
  18514. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18515. get: function () {
  18516. return this._isLocked;
  18517. },
  18518. set: function (value) {
  18519. this._isLocked = value;
  18520. },
  18521. enumerable: true,
  18522. configurable: true
  18523. });
  18524. // Methods
  18525. BoundingInfo.prototype.update = function (world) {
  18526. if (this._isLocked) {
  18527. return;
  18528. }
  18529. this.boundingBox._update(world);
  18530. this.boundingSphere._update(world);
  18531. };
  18532. /**
  18533. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18534. * @param center New center of the bounding info
  18535. * @param extend New extend of the bounding info
  18536. */
  18537. BoundingInfo.prototype.centerOn = function (center, extend) {
  18538. this.minimum = center.subtract(extend);
  18539. this.maximum = center.add(extend);
  18540. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18541. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18542. return this;
  18543. };
  18544. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18545. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18546. return false;
  18547. return this.boundingBox.isInFrustum(frustumPlanes);
  18548. };
  18549. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18550. /**
  18551. * Gets the world distance between the min and max points of the bounding box
  18552. */
  18553. get: function () {
  18554. var boundingBox = this.boundingBox;
  18555. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18556. return size.length();
  18557. },
  18558. enumerable: true,
  18559. configurable: true
  18560. });
  18561. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18562. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18563. };
  18564. BoundingInfo.prototype._checkCollision = function (collider) {
  18565. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18566. };
  18567. BoundingInfo.prototype.intersectsPoint = function (point) {
  18568. if (!this.boundingSphere.centerWorld) {
  18569. return false;
  18570. }
  18571. if (!this.boundingSphere.intersectsPoint(point)) {
  18572. return false;
  18573. }
  18574. if (!this.boundingBox.intersectsPoint(point)) {
  18575. return false;
  18576. }
  18577. return true;
  18578. };
  18579. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18580. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18581. return false;
  18582. }
  18583. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18584. return false;
  18585. }
  18586. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18587. return false;
  18588. }
  18589. if (!precise) {
  18590. return true;
  18591. }
  18592. var box0 = this.boundingBox;
  18593. var box1 = boundingInfo.boundingBox;
  18594. if (!axisOverlap(box0.directions[0], box0, box1))
  18595. return false;
  18596. if (!axisOverlap(box0.directions[1], box0, box1))
  18597. return false;
  18598. if (!axisOverlap(box0.directions[2], box0, box1))
  18599. return false;
  18600. if (!axisOverlap(box1.directions[0], box0, box1))
  18601. return false;
  18602. if (!axisOverlap(box1.directions[1], box0, box1))
  18603. return false;
  18604. if (!axisOverlap(box1.directions[2], box0, box1))
  18605. return false;
  18606. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18607. return false;
  18608. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18609. return false;
  18610. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18611. return false;
  18612. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18613. return false;
  18614. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18615. return false;
  18616. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18617. return false;
  18618. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18619. return false;
  18620. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18621. return false;
  18622. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18623. return false;
  18624. return true;
  18625. };
  18626. return BoundingInfo;
  18627. }());
  18628. BABYLON.BoundingInfo = BoundingInfo;
  18629. })(BABYLON || (BABYLON = {}));
  18630. //# sourceMappingURL=babylon.boundingInfo.js.map
  18631. var BABYLON;
  18632. (function (BABYLON) {
  18633. var TransformNode = /** @class */ (function (_super) {
  18634. __extends(TransformNode, _super);
  18635. function TransformNode(name, scene, isPure) {
  18636. if (scene === void 0) { scene = null; }
  18637. if (isPure === void 0) { isPure = true; }
  18638. var _this = _super.call(this, name, scene) || this;
  18639. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18640. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18641. _this._up = new BABYLON.Vector3(0, 1, 0);
  18642. _this._right = new BABYLON.Vector3(1, 0, 0);
  18643. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18644. // Properties
  18645. _this._rotation = BABYLON.Vector3.Zero();
  18646. _this._scaling = BABYLON.Vector3.One();
  18647. _this._isDirty = false;
  18648. /**
  18649. * Set the billboard mode. Default is 0.
  18650. *
  18651. * | Value | Type | Description |
  18652. * | --- | --- | --- |
  18653. * | 0 | BILLBOARDMODE_NONE | |
  18654. * | 1 | BILLBOARDMODE_X | |
  18655. * | 2 | BILLBOARDMODE_Y | |
  18656. * | 4 | BILLBOARDMODE_Z | |
  18657. * | 7 | BILLBOARDMODE_ALL | |
  18658. *
  18659. */
  18660. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18661. _this.scalingDeterminant = 1;
  18662. _this.infiniteDistance = false;
  18663. /**
  18664. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18665. * By default the system will update normals to compensate
  18666. */
  18667. _this.ignoreNonUniformScaling = false;
  18668. _this.position = BABYLON.Vector3.Zero();
  18669. _this._localWorld = BABYLON.Matrix.Zero();
  18670. _this._worldMatrix = BABYLON.Matrix.Zero();
  18671. _this._worldMatrixDeterminant = 0;
  18672. _this._absolutePosition = BABYLON.Vector3.Zero();
  18673. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18674. _this._postMultiplyPivotMatrix = false;
  18675. _this._isWorldMatrixFrozen = false;
  18676. /**
  18677. * An event triggered after the world matrix is updated
  18678. */
  18679. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18680. _this._nonUniformScaling = false;
  18681. if (isPure) {
  18682. _this.getScene().addTransformNode(_this);
  18683. }
  18684. return _this;
  18685. }
  18686. /**
  18687. * Gets a string idenfifying the name of the class
  18688. * @returns "TransformNode" string
  18689. */
  18690. TransformNode.prototype.getClassName = function () {
  18691. return "TransformNode";
  18692. };
  18693. Object.defineProperty(TransformNode.prototype, "rotation", {
  18694. /**
  18695. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18696. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18697. * Default : (0.0, 0.0, 0.0)
  18698. */
  18699. get: function () {
  18700. return this._rotation;
  18701. },
  18702. set: function (newRotation) {
  18703. this._rotation = newRotation;
  18704. },
  18705. enumerable: true,
  18706. configurable: true
  18707. });
  18708. Object.defineProperty(TransformNode.prototype, "scaling", {
  18709. /**
  18710. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18711. * Default : (1.0, 1.0, 1.0)
  18712. */
  18713. get: function () {
  18714. return this._scaling;
  18715. },
  18716. /**
  18717. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18718. * Default : (1.0, 1.0, 1.0)
  18719. */
  18720. set: function (newScaling) {
  18721. this._scaling = newScaling;
  18722. },
  18723. enumerable: true,
  18724. configurable: true
  18725. });
  18726. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18727. /**
  18728. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18729. * It's null by default.
  18730. * 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)
  18731. */
  18732. get: function () {
  18733. return this._rotationQuaternion;
  18734. },
  18735. set: function (quaternion) {
  18736. this._rotationQuaternion = quaternion;
  18737. //reset the rotation vector.
  18738. if (quaternion && this.rotation.length()) {
  18739. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18740. }
  18741. },
  18742. enumerable: true,
  18743. configurable: true
  18744. });
  18745. Object.defineProperty(TransformNode.prototype, "forward", {
  18746. /**
  18747. * The forward direction of that transform in world space.
  18748. */
  18749. get: function () {
  18750. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18751. },
  18752. enumerable: true,
  18753. configurable: true
  18754. });
  18755. Object.defineProperty(TransformNode.prototype, "up", {
  18756. /**
  18757. * The up direction of that transform in world space.
  18758. */
  18759. get: function () {
  18760. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. Object.defineProperty(TransformNode.prototype, "right", {
  18766. /**
  18767. * The right direction of that transform in world space.
  18768. */
  18769. get: function () {
  18770. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18771. },
  18772. enumerable: true,
  18773. configurable: true
  18774. });
  18775. /**
  18776. * Returns the latest update of the World matrix
  18777. * Returns a Matrix.
  18778. */
  18779. TransformNode.prototype.getWorldMatrix = function () {
  18780. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18781. this.computeWorldMatrix();
  18782. }
  18783. return this._worldMatrix;
  18784. };
  18785. /** @hidden */
  18786. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18787. return this._worldMatrixDeterminant;
  18788. };
  18789. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18790. /**
  18791. * Returns directly the latest state of the mesh World matrix.
  18792. * A Matrix is returned.
  18793. */
  18794. get: function () {
  18795. return this._worldMatrix;
  18796. },
  18797. enumerable: true,
  18798. configurable: true
  18799. });
  18800. /**
  18801. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18802. * Returns the TransformNode.
  18803. */
  18804. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18805. this._poseMatrix.copyFrom(matrix);
  18806. return this;
  18807. };
  18808. /**
  18809. * Returns the mesh Pose matrix.
  18810. * Returned object : Matrix
  18811. */
  18812. TransformNode.prototype.getPoseMatrix = function () {
  18813. return this._poseMatrix;
  18814. };
  18815. TransformNode.prototype._isSynchronized = function () {
  18816. if (this._isDirty) {
  18817. return false;
  18818. }
  18819. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18820. return false;
  18821. if (this._cache.pivotMatrixUpdated) {
  18822. return false;
  18823. }
  18824. if (this.infiniteDistance) {
  18825. return false;
  18826. }
  18827. if (!this._cache.position.equals(this.position))
  18828. return false;
  18829. if (this.rotationQuaternion) {
  18830. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18831. return false;
  18832. }
  18833. if (!this._cache.rotation.equals(this.rotation))
  18834. return false;
  18835. if (!this._cache.scaling.equals(this.scaling))
  18836. return false;
  18837. return true;
  18838. };
  18839. TransformNode.prototype._initCache = function () {
  18840. _super.prototype._initCache.call(this);
  18841. this._cache.localMatrixUpdated = false;
  18842. this._cache.position = BABYLON.Vector3.Zero();
  18843. this._cache.scaling = BABYLON.Vector3.Zero();
  18844. this._cache.rotation = BABYLON.Vector3.Zero();
  18845. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18846. this._cache.billboardMode = -1;
  18847. };
  18848. TransformNode.prototype.markAsDirty = function (property) {
  18849. if (property === "rotation") {
  18850. this.rotationQuaternion = null;
  18851. }
  18852. this._currentRenderId = Number.MAX_VALUE;
  18853. this._isDirty = true;
  18854. return this;
  18855. };
  18856. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18857. /**
  18858. * Returns the current mesh absolute position.
  18859. * Retuns a Vector3.
  18860. */
  18861. get: function () {
  18862. return this._absolutePosition;
  18863. },
  18864. enumerable: true,
  18865. configurable: true
  18866. });
  18867. /**
  18868. * Sets a new matrix to apply before all other transformation
  18869. * @param matrix defines the transform matrix
  18870. * @returns the current TransformNode
  18871. */
  18872. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18873. return this.setPivotMatrix(matrix, false);
  18874. };
  18875. /**
  18876. * Sets a new pivot matrix to the current node
  18877. * @param matrix defines the new pivot matrix to use
  18878. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  18879. * @returns the current TransformNode
  18880. */
  18881. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18882. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18883. this._pivotMatrix = matrix.clone();
  18884. this._cache.pivotMatrixUpdated = true;
  18885. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18886. if (this._postMultiplyPivotMatrix) {
  18887. if (!this._pivotMatrixInverse) {
  18888. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18889. }
  18890. else {
  18891. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18892. }
  18893. }
  18894. return this;
  18895. };
  18896. /**
  18897. * Returns the mesh pivot matrix.
  18898. * Default : Identity.
  18899. * A Matrix is returned.
  18900. */
  18901. TransformNode.prototype.getPivotMatrix = function () {
  18902. return this._pivotMatrix;
  18903. };
  18904. /**
  18905. * Prevents the World matrix to be computed any longer.
  18906. * Returns the TransformNode.
  18907. */
  18908. TransformNode.prototype.freezeWorldMatrix = function () {
  18909. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18910. this.computeWorldMatrix(true);
  18911. this._isWorldMatrixFrozen = true;
  18912. return this;
  18913. };
  18914. /**
  18915. * Allows back the World matrix computation.
  18916. * Returns the TransformNode.
  18917. */
  18918. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18919. this._isWorldMatrixFrozen = false;
  18920. this.computeWorldMatrix(true);
  18921. return this;
  18922. };
  18923. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18924. /**
  18925. * True if the World matrix has been frozen.
  18926. * Returns a boolean.
  18927. */
  18928. get: function () {
  18929. return this._isWorldMatrixFrozen;
  18930. },
  18931. enumerable: true,
  18932. configurable: true
  18933. });
  18934. /**
  18935. * Retuns the mesh absolute position in the World.
  18936. * Returns a Vector3.
  18937. */
  18938. TransformNode.prototype.getAbsolutePosition = function () {
  18939. this.computeWorldMatrix();
  18940. return this._absolutePosition;
  18941. };
  18942. /**
  18943. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18944. * Returns the TransformNode.
  18945. */
  18946. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18947. if (!absolutePosition) {
  18948. return this;
  18949. }
  18950. var absolutePositionX;
  18951. var absolutePositionY;
  18952. var absolutePositionZ;
  18953. if (absolutePosition.x === undefined) {
  18954. if (arguments.length < 3) {
  18955. return this;
  18956. }
  18957. absolutePositionX = arguments[0];
  18958. absolutePositionY = arguments[1];
  18959. absolutePositionZ = arguments[2];
  18960. }
  18961. else {
  18962. absolutePositionX = absolutePosition.x;
  18963. absolutePositionY = absolutePosition.y;
  18964. absolutePositionZ = absolutePosition.z;
  18965. }
  18966. if (this.parent) {
  18967. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18968. invertParentWorldMatrix.invert();
  18969. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18970. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18971. }
  18972. else {
  18973. this.position.x = absolutePositionX;
  18974. this.position.y = absolutePositionY;
  18975. this.position.z = absolutePositionZ;
  18976. }
  18977. return this;
  18978. };
  18979. /**
  18980. * Sets the mesh position in its local space.
  18981. * Returns the TransformNode.
  18982. */
  18983. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18984. this.computeWorldMatrix();
  18985. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18986. return this;
  18987. };
  18988. /**
  18989. * Returns the mesh position in the local space from the current World matrix values.
  18990. * Returns a new Vector3.
  18991. */
  18992. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18993. this.computeWorldMatrix();
  18994. var invLocalWorldMatrix = this._localWorld.clone();
  18995. invLocalWorldMatrix.invert();
  18996. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18997. };
  18998. /**
  18999. * Translates the mesh along the passed Vector3 in its local space.
  19000. * Returns the TransformNode.
  19001. */
  19002. TransformNode.prototype.locallyTranslate = function (vector3) {
  19003. this.computeWorldMatrix(true);
  19004. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19005. return this;
  19006. };
  19007. /**
  19008. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19009. * @param targetPoint the position (must be in same space as current mesh) to look at
  19010. * @param yawCor optional yaw (y-axis) correction in radians
  19011. * @param pitchCor optional pitch (x-axis) correction in radians
  19012. * @param rollCor optional roll (z-axis) correction in radians
  19013. * @param space the choosen space of the target
  19014. * @returns the TransformNode.
  19015. */
  19016. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19017. if (yawCor === void 0) { yawCor = 0; }
  19018. if (pitchCor === void 0) { pitchCor = 0; }
  19019. if (rollCor === void 0) { rollCor = 0; }
  19020. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19021. var dv = TransformNode._lookAtVectorCache;
  19022. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19023. targetPoint.subtractToRef(pos, dv);
  19024. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19025. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19026. var pitch = Math.atan2(dv.y, len);
  19027. if (this.rotationQuaternion) {
  19028. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19029. }
  19030. else {
  19031. this.rotation.x = pitch + pitchCor;
  19032. this.rotation.y = yaw + yawCor;
  19033. this.rotation.z = rollCor;
  19034. }
  19035. return this;
  19036. };
  19037. /**
  19038. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19039. * This Vector3 is expressed in the World space.
  19040. */
  19041. TransformNode.prototype.getDirection = function (localAxis) {
  19042. var result = BABYLON.Vector3.Zero();
  19043. this.getDirectionToRef(localAxis, result);
  19044. return result;
  19045. };
  19046. /**
  19047. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19048. * localAxis is expressed in the mesh local space.
  19049. * result is computed in the Wordl space from the mesh World matrix.
  19050. * Returns the TransformNode.
  19051. */
  19052. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19053. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19054. return this;
  19055. };
  19056. /**
  19057. * Sets a new pivot point to the current node
  19058. * @param point defines the new pivot point to use
  19059. * @param space defines if the point is in world or local space (local by default)
  19060. * @returns the current TransformNode
  19061. */
  19062. TransformNode.prototype.setPivotPoint = function (point, space) {
  19063. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19064. if (this.getScene().getRenderId() == 0) {
  19065. this.computeWorldMatrix(true);
  19066. }
  19067. var wm = this.getWorldMatrix();
  19068. if (space == BABYLON.Space.WORLD) {
  19069. var tmat = BABYLON.Tmp.Matrix[0];
  19070. wm.invertToRef(tmat);
  19071. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19072. }
  19073. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19074. };
  19075. /**
  19076. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19077. */
  19078. TransformNode.prototype.getPivotPoint = function () {
  19079. var point = BABYLON.Vector3.Zero();
  19080. this.getPivotPointToRef(point);
  19081. return point;
  19082. };
  19083. /**
  19084. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19085. * Returns the TransformNode.
  19086. */
  19087. TransformNode.prototype.getPivotPointToRef = function (result) {
  19088. result.x = -this._pivotMatrix.m[12];
  19089. result.y = -this._pivotMatrix.m[13];
  19090. result.z = -this._pivotMatrix.m[14];
  19091. return this;
  19092. };
  19093. /**
  19094. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19095. */
  19096. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19097. var point = BABYLON.Vector3.Zero();
  19098. this.getAbsolutePivotPointToRef(point);
  19099. return point;
  19100. };
  19101. /**
  19102. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19103. * Returns the TransformNode.
  19104. */
  19105. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19106. result.x = this._pivotMatrix.m[12];
  19107. result.y = this._pivotMatrix.m[13];
  19108. result.z = this._pivotMatrix.m[14];
  19109. this.getPivotPointToRef(result);
  19110. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19111. return this;
  19112. };
  19113. /**
  19114. * Defines the passed node as the parent of the current node.
  19115. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19116. * Returns the TransformNode.
  19117. */
  19118. TransformNode.prototype.setParent = function (node) {
  19119. if (!node && !this.parent) {
  19120. return this;
  19121. }
  19122. if (!node) {
  19123. var rotation = BABYLON.Tmp.Quaternion[0];
  19124. var position = BABYLON.Tmp.Vector3[0];
  19125. var scale = BABYLON.Tmp.Vector3[1];
  19126. if (this.parent && this.parent.computeWorldMatrix) {
  19127. this.parent.computeWorldMatrix(true);
  19128. }
  19129. this.computeWorldMatrix(true);
  19130. this.getWorldMatrix().decompose(scale, rotation, position);
  19131. if (this.rotationQuaternion) {
  19132. this.rotationQuaternion.copyFrom(rotation);
  19133. }
  19134. else {
  19135. rotation.toEulerAnglesToRef(this.rotation);
  19136. }
  19137. this.scaling.x = scale.x;
  19138. this.scaling.y = scale.y;
  19139. this.scaling.z = scale.z;
  19140. this.position.x = position.x;
  19141. this.position.y = position.y;
  19142. this.position.z = position.z;
  19143. }
  19144. else {
  19145. var rotation = BABYLON.Tmp.Quaternion[0];
  19146. var position = BABYLON.Tmp.Vector3[0];
  19147. var scale = BABYLON.Tmp.Vector3[1];
  19148. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19149. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19150. this.computeWorldMatrix(true);
  19151. node.computeWorldMatrix(true);
  19152. node.getWorldMatrix().invertToRef(invParentMatrix);
  19153. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19154. diffMatrix.decompose(scale, rotation, position);
  19155. if (this.rotationQuaternion) {
  19156. this.rotationQuaternion.copyFrom(rotation);
  19157. }
  19158. else {
  19159. rotation.toEulerAnglesToRef(this.rotation);
  19160. }
  19161. this.position.x = position.x;
  19162. this.position.y = position.y;
  19163. this.position.z = position.z;
  19164. this.scaling.x = scale.x;
  19165. this.scaling.y = scale.y;
  19166. this.scaling.z = scale.z;
  19167. }
  19168. this.parent = node;
  19169. return this;
  19170. };
  19171. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19172. get: function () {
  19173. return this._nonUniformScaling;
  19174. },
  19175. enumerable: true,
  19176. configurable: true
  19177. });
  19178. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19179. if (this._nonUniformScaling === value) {
  19180. return false;
  19181. }
  19182. this._nonUniformScaling = value;
  19183. return true;
  19184. };
  19185. /**
  19186. * Attach the current TransformNode to another TransformNode associated with a bone
  19187. * @param bone Bone affecting the TransformNode
  19188. * @param affectedTransformNode TransformNode associated with the bone
  19189. */
  19190. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19191. this._transformToBoneReferal = affectedTransformNode;
  19192. this.parent = bone;
  19193. if (bone.getWorldMatrix().determinant() < 0) {
  19194. this.scalingDeterminant *= -1;
  19195. }
  19196. return this;
  19197. };
  19198. TransformNode.prototype.detachFromBone = function () {
  19199. if (!this.parent) {
  19200. return this;
  19201. }
  19202. if (this.parent.getWorldMatrix().determinant() < 0) {
  19203. this.scalingDeterminant *= -1;
  19204. }
  19205. this._transformToBoneReferal = null;
  19206. this.parent = null;
  19207. return this;
  19208. };
  19209. /**
  19210. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19211. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19212. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19213. * The passed axis is also normalized.
  19214. * Returns the TransformNode.
  19215. */
  19216. TransformNode.prototype.rotate = function (axis, amount, space) {
  19217. axis.normalize();
  19218. if (!this.rotationQuaternion) {
  19219. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19220. this.rotation = BABYLON.Vector3.Zero();
  19221. }
  19222. var rotationQuaternion;
  19223. if (!space || space === BABYLON.Space.LOCAL) {
  19224. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19225. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19226. }
  19227. else {
  19228. if (this.parent) {
  19229. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19230. invertParentWorldMatrix.invert();
  19231. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19232. }
  19233. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19234. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19235. }
  19236. return this;
  19237. };
  19238. /**
  19239. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19240. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19241. * The passed axis is also normalized.
  19242. * Returns the TransformNode.
  19243. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19244. */
  19245. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19246. axis.normalize();
  19247. if (!this.rotationQuaternion) {
  19248. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19249. this.rotation.copyFromFloats(0, 0, 0);
  19250. }
  19251. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19252. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19253. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19254. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19255. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19256. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19257. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19258. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19259. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19260. return this;
  19261. };
  19262. /**
  19263. * Translates the mesh along the axis vector for the passed distance in the given space.
  19264. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19265. * Returns the TransformNode.
  19266. */
  19267. TransformNode.prototype.translate = function (axis, distance, space) {
  19268. var displacementVector = axis.scale(distance);
  19269. if (!space || space === BABYLON.Space.LOCAL) {
  19270. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19271. this.setPositionWithLocalVector(tempV3);
  19272. }
  19273. else {
  19274. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19275. }
  19276. return this;
  19277. };
  19278. /**
  19279. * Adds a rotation step to the mesh current rotation.
  19280. * x, y, z are Euler angles expressed in radians.
  19281. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19282. * This means this rotation is made in the mesh local space only.
  19283. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19284. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19285. * ```javascript
  19286. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19287. * ```
  19288. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19289. * 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.
  19290. * Returns the TransformNode.
  19291. */
  19292. TransformNode.prototype.addRotation = function (x, y, z) {
  19293. var rotationQuaternion;
  19294. if (this.rotationQuaternion) {
  19295. rotationQuaternion = this.rotationQuaternion;
  19296. }
  19297. else {
  19298. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19299. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19300. }
  19301. var accumulation = BABYLON.Tmp.Quaternion[0];
  19302. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19303. rotationQuaternion.multiplyInPlace(accumulation);
  19304. if (!this.rotationQuaternion) {
  19305. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19306. }
  19307. return this;
  19308. };
  19309. /**
  19310. * Computes the mesh World matrix and returns it.
  19311. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19312. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19313. * If the parameter `force`is set to `true`, the actual computation is done.
  19314. * Returns the mesh World Matrix.
  19315. */
  19316. TransformNode.prototype.computeWorldMatrix = function (force) {
  19317. if (this._isWorldMatrixFrozen) {
  19318. return this._worldMatrix;
  19319. }
  19320. if (!force && this.isSynchronized(true)) {
  19321. this._currentRenderId = this.getScene().getRenderId();
  19322. return this._worldMatrix;
  19323. }
  19324. this._cache.position.copyFrom(this.position);
  19325. this._cache.scaling.copyFrom(this.scaling);
  19326. this._cache.pivotMatrixUpdated = false;
  19327. this._cache.billboardMode = this.billboardMode;
  19328. this._currentRenderId = this.getScene().getRenderId();
  19329. this._childRenderId = this.getScene().getRenderId();
  19330. this._isDirty = false;
  19331. // Scaling
  19332. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19333. // Rotation
  19334. //rotate, if quaternion is set and rotation was used
  19335. if (this.rotationQuaternion) {
  19336. var len = this.rotation.length();
  19337. if (len) {
  19338. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19339. this.rotation.copyFromFloats(0, 0, 0);
  19340. }
  19341. }
  19342. if (this.rotationQuaternion) {
  19343. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19344. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19345. }
  19346. else {
  19347. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19348. this._cache.rotation.copyFrom(this.rotation);
  19349. }
  19350. // Translation
  19351. var camera = this.getScene().activeCamera;
  19352. if (this.infiniteDistance && !this.parent && camera) {
  19353. var cameraWorldMatrix = camera.getWorldMatrix();
  19354. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19355. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19356. }
  19357. else {
  19358. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19359. }
  19360. // Composing transformations
  19361. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19362. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19363. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19364. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19365. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19366. // Need to decompose each rotation here
  19367. var currentPosition = BABYLON.Tmp.Vector3[3];
  19368. if (this.parent && this.parent.getWorldMatrix) {
  19369. if (this._transformToBoneReferal) {
  19370. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19371. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19372. }
  19373. else {
  19374. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19375. }
  19376. }
  19377. else {
  19378. currentPosition.copyFrom(this.position);
  19379. }
  19380. currentPosition.subtractInPlace(camera.globalPosition);
  19381. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19382. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19383. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19384. }
  19385. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19386. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19387. }
  19388. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19389. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19390. }
  19391. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19392. }
  19393. else {
  19394. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19395. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19396. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19397. }
  19398. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19399. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19400. }
  19401. // Local world
  19402. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19403. // Parent
  19404. if (this.parent && this.parent.getWorldMatrix) {
  19405. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19406. if (this._transformToBoneReferal) {
  19407. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19408. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19409. }
  19410. else {
  19411. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19412. }
  19413. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19414. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19415. this._worldMatrix.copyFrom(this._localWorld);
  19416. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19417. }
  19418. else {
  19419. if (this._transformToBoneReferal) {
  19420. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19421. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19422. }
  19423. else {
  19424. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19425. }
  19426. }
  19427. this._markSyncedWithParent();
  19428. }
  19429. else {
  19430. this._worldMatrix.copyFrom(this._localWorld);
  19431. }
  19432. // Post multiply inverse of pivotMatrix
  19433. if (this._postMultiplyPivotMatrix) {
  19434. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19435. }
  19436. // Normal matrix
  19437. if (!this.ignoreNonUniformScaling) {
  19438. if (this.scaling.isNonUniform) {
  19439. this._updateNonUniformScalingState(true);
  19440. }
  19441. else if (this.parent && this.parent._nonUniformScaling) {
  19442. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19443. }
  19444. else {
  19445. this._updateNonUniformScalingState(false);
  19446. }
  19447. }
  19448. else {
  19449. this._updateNonUniformScalingState(false);
  19450. }
  19451. this._afterComputeWorldMatrix();
  19452. // Absolute position
  19453. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19454. // Callbacks
  19455. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19456. if (!this._poseMatrix) {
  19457. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19458. }
  19459. // Cache the determinant
  19460. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19461. return this._worldMatrix;
  19462. };
  19463. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19464. };
  19465. /**
  19466. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19467. * @param func: callback function to add
  19468. *
  19469. * Returns the TransformNode.
  19470. */
  19471. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19472. this.onAfterWorldMatrixUpdateObservable.add(func);
  19473. return this;
  19474. };
  19475. /**
  19476. * Removes a registered callback function.
  19477. * Returns the TransformNode.
  19478. */
  19479. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19480. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19481. return this;
  19482. };
  19483. /**
  19484. * Clone the current transform node
  19485. * Returns the new transform node
  19486. * @param name Name of the new clone
  19487. * @param newParent New parent for the clone
  19488. * @param doNotCloneChildren Do not clone children hierarchy
  19489. */
  19490. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19491. var _this = this;
  19492. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19493. result.name = name;
  19494. result.id = name;
  19495. if (newParent) {
  19496. result.parent = newParent;
  19497. }
  19498. if (!doNotCloneChildren) {
  19499. // Children
  19500. var directDescendants = this.getDescendants(true);
  19501. for (var index = 0; index < directDescendants.length; index++) {
  19502. var child = directDescendants[index];
  19503. if (child.clone) {
  19504. child.clone(name + "." + child.name, result);
  19505. }
  19506. }
  19507. }
  19508. return result;
  19509. };
  19510. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19511. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19512. serializationObject.type = this.getClassName();
  19513. // Parent
  19514. if (this.parent) {
  19515. serializationObject.parentId = this.parent.id;
  19516. }
  19517. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19518. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19519. }
  19520. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19521. serializationObject.isEnabled = this.isEnabled();
  19522. // Parent
  19523. if (this.parent) {
  19524. serializationObject.parentId = this.parent.id;
  19525. }
  19526. return serializationObject;
  19527. };
  19528. // Statics
  19529. /**
  19530. * Returns a new TransformNode object parsed from the source provided.
  19531. * The parameter `parsedMesh` is the source.
  19532. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19533. */
  19534. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19535. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19536. if (BABYLON.Tags) {
  19537. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19538. }
  19539. if (parsedTransformNode.localMatrix) {
  19540. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19541. }
  19542. else if (parsedTransformNode.pivotMatrix) {
  19543. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19544. }
  19545. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19546. // Parent
  19547. if (parsedTransformNode.parentId) {
  19548. transformNode._waitingParentId = parsedTransformNode.parentId;
  19549. }
  19550. return transformNode;
  19551. };
  19552. /**
  19553. * Releases resources associated with this transform node.
  19554. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19555. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19556. */
  19557. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19558. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19559. // Animations
  19560. this.getScene().stopAnimation(this);
  19561. // Remove from scene
  19562. this.getScene().removeTransformNode(this);
  19563. this.onAfterWorldMatrixUpdateObservable.clear();
  19564. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19565. };
  19566. // Statics
  19567. TransformNode.BILLBOARDMODE_NONE = 0;
  19568. TransformNode.BILLBOARDMODE_X = 1;
  19569. TransformNode.BILLBOARDMODE_Y = 2;
  19570. TransformNode.BILLBOARDMODE_Z = 4;
  19571. TransformNode.BILLBOARDMODE_ALL = 7;
  19572. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19573. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19574. __decorate([
  19575. BABYLON.serializeAsVector3()
  19576. ], TransformNode.prototype, "_rotation", void 0);
  19577. __decorate([
  19578. BABYLON.serializeAsQuaternion()
  19579. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19580. __decorate([
  19581. BABYLON.serializeAsVector3()
  19582. ], TransformNode.prototype, "_scaling", void 0);
  19583. __decorate([
  19584. BABYLON.serialize()
  19585. ], TransformNode.prototype, "billboardMode", void 0);
  19586. __decorate([
  19587. BABYLON.serialize()
  19588. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19589. __decorate([
  19590. BABYLON.serialize()
  19591. ], TransformNode.prototype, "infiniteDistance", void 0);
  19592. __decorate([
  19593. BABYLON.serialize()
  19594. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19595. __decorate([
  19596. BABYLON.serializeAsVector3()
  19597. ], TransformNode.prototype, "position", void 0);
  19598. return TransformNode;
  19599. }(BABYLON.Node));
  19600. BABYLON.TransformNode = TransformNode;
  19601. })(BABYLON || (BABYLON = {}));
  19602. //# sourceMappingURL=babylon.transformNode.js.map
  19603. var BABYLON;
  19604. (function (BABYLON) {
  19605. /**
  19606. * Class used to store all common mesh properties
  19607. */
  19608. var AbstractMesh = /** @class */ (function (_super) {
  19609. __extends(AbstractMesh, _super);
  19610. // Constructor
  19611. /**
  19612. * Creates a new AbstractMesh
  19613. * @param name defines the name of the mesh
  19614. * @param scene defines the hosting scene
  19615. */
  19616. function AbstractMesh(name, scene) {
  19617. if (scene === void 0) { scene = null; }
  19618. var _this = _super.call(this, name, scene, false) || this;
  19619. _this._facetNb = 0; // facet number
  19620. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19621. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19622. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19623. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19624. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19625. _this._subDiv = {
  19626. max: 1,
  19627. X: 1,
  19628. Y: 1,
  19629. Z: 1
  19630. };
  19631. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19632. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19633. // Events
  19634. /**
  19635. * An event triggered when this mesh collides with another one
  19636. */
  19637. _this.onCollideObservable = new BABYLON.Observable();
  19638. /**
  19639. * An event triggered when the collision's position changes
  19640. */
  19641. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19642. /**
  19643. * An event triggered when material is changed
  19644. */
  19645. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19646. // Properties
  19647. /**
  19648. * Gets or sets the orientation for POV movement & rotation
  19649. */
  19650. _this.definedFacingForward = true;
  19651. /**
  19652. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19653. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19654. * * 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.
  19655. * @see http://doc.babylonjs.com/features/occlusionquery
  19656. */
  19657. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19658. /**
  19659. * 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:
  19660. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19661. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19662. * * 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.
  19663. * @see http://doc.babylonjs.com/features/occlusionquery
  19664. */
  19665. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19666. /**
  19667. * 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.
  19668. * The default value is -1 which means don't break the query and wait till the result
  19669. * @see http://doc.babylonjs.com/features/occlusionquery
  19670. */
  19671. _this.occlusionRetryCount = -1;
  19672. _this._occlusionInternalRetryCounter = 0;
  19673. _this._isOccluded = false;
  19674. _this._isOcclusionQueryInProgress = false;
  19675. _this._visibility = 1.0;
  19676. /** Gets or sets the alpha index used to sort transparent meshes
  19677. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19678. */
  19679. _this.alphaIndex = Number.MAX_VALUE;
  19680. /**
  19681. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19682. */
  19683. _this.isVisible = true;
  19684. /**
  19685. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19686. */
  19687. _this.isPickable = true;
  19688. /**
  19689. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19690. */
  19691. _this.showBoundingBox = false;
  19692. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19693. _this.showSubMeshesBoundingBox = false;
  19694. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19695. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19696. */
  19697. _this.isBlocker = false;
  19698. /**
  19699. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19700. */
  19701. _this.enablePointerMoveEvents = false;
  19702. /**
  19703. * Specifies the rendering group id for this mesh (0 by default)
  19704. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19705. */
  19706. _this.renderingGroupId = 0;
  19707. _this._receiveShadows = false;
  19708. /**
  19709. * Gets or sets a boolean indicating if the outline must be rendered as well
  19710. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19711. */
  19712. _this.renderOutline = false;
  19713. /** Defines color to use when rendering outline */
  19714. _this.outlineColor = BABYLON.Color3.Red();
  19715. /** Define width to use when rendering outline */
  19716. _this.outlineWidth = 0.02;
  19717. /**
  19718. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19719. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19720. */
  19721. _this.renderOverlay = false;
  19722. /** Defines color to use when rendering overlay */
  19723. _this.overlayColor = BABYLON.Color3.Red();
  19724. /** Defines alpha to use when rendering overlay */
  19725. _this.overlayAlpha = 0.5;
  19726. _this._hasVertexAlpha = false;
  19727. _this._useVertexColors = true;
  19728. _this._computeBonesUsingShaders = true;
  19729. _this._numBoneInfluencers = 4;
  19730. _this._applyFog = true;
  19731. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19732. _this.useOctreeForRenderingSelection = true;
  19733. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19734. _this.useOctreeForPicking = true;
  19735. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19736. _this.useOctreeForCollisions = true;
  19737. _this._layerMask = 0x0FFFFFFF;
  19738. /**
  19739. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19740. */
  19741. _this.alwaysSelectAsActiveMesh = false;
  19742. /**
  19743. * Gets or sets the current action manager
  19744. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19745. */
  19746. _this.actionManager = null;
  19747. /**
  19748. * Gets or sets impostor used for physic simulation
  19749. * @see http://doc.babylonjs.com/features/physics_engine
  19750. */
  19751. _this.physicsImpostor = null;
  19752. // Collisions
  19753. _this._checkCollisions = false;
  19754. _this._collisionMask = -1;
  19755. _this._collisionGroup = -1;
  19756. /**
  19757. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19758. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19759. */
  19760. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19761. /**
  19762. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19763. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19764. */
  19765. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19766. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19767. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19768. // Edges
  19769. /**
  19770. * Defines edge width used when edgesRenderer is enabled
  19771. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19772. */
  19773. _this.edgesWidth = 1;
  19774. /**
  19775. * Defines edge color used when edgesRenderer is enabled
  19776. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19777. */
  19778. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19779. // Cache
  19780. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19781. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19782. /** @hidden */
  19783. _this._renderId = 0;
  19784. /** @hidden */
  19785. _this._intersectionsInProgress = new Array();
  19786. /** @hidden */
  19787. _this._unIndexed = false;
  19788. /** @hidden */
  19789. _this._lightSources = new Array();
  19790. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19791. if (collidedMesh === void 0) { collidedMesh = null; }
  19792. //TODO move this to the collision coordinator!
  19793. if (_this.getScene().workerCollisions)
  19794. newPosition.multiplyInPlace(_this._collider._radius);
  19795. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19796. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19797. _this.position.addInPlace(_this._diffPositionForCollisions);
  19798. }
  19799. if (collidedMesh) {
  19800. _this.onCollideObservable.notifyObservers(collidedMesh);
  19801. }
  19802. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19803. };
  19804. _this.getScene().addMesh(_this);
  19805. _this._resyncLightSources();
  19806. return _this;
  19807. }
  19808. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19809. /**
  19810. * No billboard
  19811. */
  19812. get: function () {
  19813. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19819. /** Billboard on X axis */
  19820. get: function () {
  19821. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19822. },
  19823. enumerable: true,
  19824. configurable: true
  19825. });
  19826. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19827. /** Billboard on Y axis */
  19828. get: function () {
  19829. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19830. },
  19831. enumerable: true,
  19832. configurable: true
  19833. });
  19834. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19835. /** Billboard on Z axis */
  19836. get: function () {
  19837. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19843. /** Billboard on all axes */
  19844. get: function () {
  19845. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19846. },
  19847. enumerable: true,
  19848. configurable: true
  19849. });
  19850. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19851. /**
  19852. * Gets the number of facets in the mesh
  19853. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19854. */
  19855. get: function () {
  19856. return this._facetNb;
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19862. /**
  19863. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19864. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19865. */
  19866. get: function () {
  19867. return this._partitioningSubdivisions;
  19868. },
  19869. set: function (nb) {
  19870. this._partitioningSubdivisions = nb;
  19871. },
  19872. enumerable: true,
  19873. configurable: true
  19874. });
  19875. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19876. /**
  19877. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19878. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19879. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19880. */
  19881. get: function () {
  19882. return this._partitioningBBoxRatio;
  19883. },
  19884. set: function (ratio) {
  19885. this._partitioningBBoxRatio = ratio;
  19886. },
  19887. enumerable: true,
  19888. configurable: true
  19889. });
  19890. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19891. /**
  19892. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19893. * Works only for updatable meshes.
  19894. * Doesn't work with multi-materials
  19895. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19896. */
  19897. get: function () {
  19898. return this._facetDepthSort;
  19899. },
  19900. set: function (sort) {
  19901. this._facetDepthSort = sort;
  19902. },
  19903. enumerable: true,
  19904. configurable: true
  19905. });
  19906. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19907. /**
  19908. * The location (Vector3) where the facet depth sort must be computed from.
  19909. * By default, the active camera position.
  19910. * Used only when facet depth sort is enabled
  19911. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19912. */
  19913. get: function () {
  19914. return this._facetDepthSortFrom;
  19915. },
  19916. set: function (location) {
  19917. this._facetDepthSortFrom = location;
  19918. },
  19919. enumerable: true,
  19920. configurable: true
  19921. });
  19922. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19923. /**
  19924. * gets a boolean indicating if facetData is enabled
  19925. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19926. */
  19927. get: function () {
  19928. return this._facetDataEnabled;
  19929. },
  19930. enumerable: true,
  19931. configurable: true
  19932. });
  19933. /** @hidden */
  19934. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19935. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19936. return false;
  19937. }
  19938. this._markSubMeshesAsMiscDirty();
  19939. return true;
  19940. };
  19941. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19942. /** Set a function to call when this mesh collides with another one */
  19943. set: function (callback) {
  19944. if (this._onCollideObserver) {
  19945. this.onCollideObservable.remove(this._onCollideObserver);
  19946. }
  19947. this._onCollideObserver = this.onCollideObservable.add(callback);
  19948. },
  19949. enumerable: true,
  19950. configurable: true
  19951. });
  19952. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19953. /** Set a function to call when the collision's position changes */
  19954. set: function (callback) {
  19955. if (this._onCollisionPositionChangeObserver) {
  19956. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19957. }
  19958. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19959. },
  19960. enumerable: true,
  19961. configurable: true
  19962. });
  19963. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19964. /**
  19965. * 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
  19966. * @see http://doc.babylonjs.com/features/occlusionquery
  19967. */
  19968. get: function () {
  19969. return this._isOccluded;
  19970. },
  19971. set: function (value) {
  19972. this._isOccluded = value;
  19973. },
  19974. enumerable: true,
  19975. configurable: true
  19976. });
  19977. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19978. /**
  19979. * Flag to check the progress status of the query
  19980. * @see http://doc.babylonjs.com/features/occlusionquery
  19981. */
  19982. get: function () {
  19983. return this._isOcclusionQueryInProgress;
  19984. },
  19985. enumerable: true,
  19986. configurable: true
  19987. });
  19988. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19989. /**
  19990. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19991. */
  19992. get: function () {
  19993. return this._visibility;
  19994. },
  19995. /**
  19996. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19997. */
  19998. set: function (value) {
  19999. if (this._visibility === value) {
  20000. return;
  20001. }
  20002. this._visibility = value;
  20003. this._markSubMeshesAsMiscDirty();
  20004. },
  20005. enumerable: true,
  20006. configurable: true
  20007. });
  20008. Object.defineProperty(AbstractMesh.prototype, "material", {
  20009. /** Gets or sets current material */
  20010. get: function () {
  20011. return this._material;
  20012. },
  20013. set: function (value) {
  20014. if (this._material === value) {
  20015. return;
  20016. }
  20017. this._material = value;
  20018. if (this.onMaterialChangedObservable.hasObservers) {
  20019. this.onMaterialChangedObservable.notifyObservers(this);
  20020. }
  20021. if (!this.subMeshes) {
  20022. return;
  20023. }
  20024. this._unBindEffect();
  20025. },
  20026. enumerable: true,
  20027. configurable: true
  20028. });
  20029. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20030. /**
  20031. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20032. * @see http://doc.babylonjs.com/babylon101/shadows
  20033. */
  20034. get: function () {
  20035. return this._receiveShadows;
  20036. },
  20037. set: function (value) {
  20038. if (this._receiveShadows === value) {
  20039. return;
  20040. }
  20041. this._receiveShadows = value;
  20042. this._markSubMeshesAsLightDirty();
  20043. },
  20044. enumerable: true,
  20045. configurable: true
  20046. });
  20047. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20048. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20049. get: function () {
  20050. return this._hasVertexAlpha;
  20051. },
  20052. set: function (value) {
  20053. if (this._hasVertexAlpha === value) {
  20054. return;
  20055. }
  20056. this._hasVertexAlpha = value;
  20057. this._markSubMeshesAsAttributesDirty();
  20058. this._markSubMeshesAsMiscDirty();
  20059. },
  20060. enumerable: true,
  20061. configurable: true
  20062. });
  20063. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20064. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  20065. get: function () {
  20066. return this._useVertexColors;
  20067. },
  20068. set: function (value) {
  20069. if (this._useVertexColors === value) {
  20070. return;
  20071. }
  20072. this._useVertexColors = value;
  20073. this._markSubMeshesAsAttributesDirty();
  20074. },
  20075. enumerable: true,
  20076. configurable: true
  20077. });
  20078. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20079. /**
  20080. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20081. */
  20082. get: function () {
  20083. return this._computeBonesUsingShaders;
  20084. },
  20085. set: function (value) {
  20086. if (this._computeBonesUsingShaders === value) {
  20087. return;
  20088. }
  20089. this._computeBonesUsingShaders = value;
  20090. this._markSubMeshesAsAttributesDirty();
  20091. },
  20092. enumerable: true,
  20093. configurable: true
  20094. });
  20095. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20096. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20097. get: function () {
  20098. return this._numBoneInfluencers;
  20099. },
  20100. set: function (value) {
  20101. if (this._numBoneInfluencers === value) {
  20102. return;
  20103. }
  20104. this._numBoneInfluencers = value;
  20105. this._markSubMeshesAsAttributesDirty();
  20106. },
  20107. enumerable: true,
  20108. configurable: true
  20109. });
  20110. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20111. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20112. get: function () {
  20113. return this._applyFog;
  20114. },
  20115. set: function (value) {
  20116. if (this._applyFog === value) {
  20117. return;
  20118. }
  20119. this._applyFog = value;
  20120. this._markSubMeshesAsMiscDirty();
  20121. },
  20122. enumerable: true,
  20123. configurable: true
  20124. });
  20125. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20126. /**
  20127. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20128. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20129. */
  20130. get: function () {
  20131. return this._layerMask;
  20132. },
  20133. set: function (value) {
  20134. if (value === this._layerMask) {
  20135. return;
  20136. }
  20137. this._layerMask = value;
  20138. this._resyncLightSources();
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20144. /**
  20145. * Gets or sets a collision mask used to mask collisions (default is -1).
  20146. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20147. */
  20148. get: function () {
  20149. return this._collisionMask;
  20150. },
  20151. set: function (mask) {
  20152. this._collisionMask = !isNaN(mask) ? mask : -1;
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20158. /**
  20159. * Gets or sets the current collision group mask (-1 by default).
  20160. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20161. */
  20162. get: function () {
  20163. return this._collisionGroup;
  20164. },
  20165. set: function (mask) {
  20166. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20167. },
  20168. enumerable: true,
  20169. configurable: true
  20170. });
  20171. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20172. /** @hidden */
  20173. get: function () {
  20174. return null;
  20175. },
  20176. enumerable: true,
  20177. configurable: true
  20178. });
  20179. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20180. get: function () {
  20181. return this._skeleton;
  20182. },
  20183. /**
  20184. * Gets or sets a skeleton to apply skining transformations
  20185. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20186. */
  20187. set: function (value) {
  20188. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20189. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20190. }
  20191. if (value && value.needInitialSkinMatrix) {
  20192. value._registerMeshWithPoseMatrix(this);
  20193. }
  20194. this._skeleton = value;
  20195. if (!this._skeleton) {
  20196. this._bonesTransformMatrices = null;
  20197. }
  20198. this._markSubMeshesAsAttributesDirty();
  20199. },
  20200. enumerable: true,
  20201. configurable: true
  20202. });
  20203. /**
  20204. * Returns the string "AbstractMesh"
  20205. * @returns "AbstractMesh"
  20206. */
  20207. AbstractMesh.prototype.getClassName = function () {
  20208. return "AbstractMesh";
  20209. };
  20210. /**
  20211. * Gets a string representation of the current mesh
  20212. * @param fullDetails defines a boolean indicating if full details must be included
  20213. * @returns a string representation of the current mesh
  20214. */
  20215. AbstractMesh.prototype.toString = function (fullDetails) {
  20216. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20217. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20218. if (this._skeleton) {
  20219. ret += ", skeleton: " + this._skeleton.name;
  20220. }
  20221. if (fullDetails) {
  20222. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20223. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20224. }
  20225. return ret;
  20226. };
  20227. /** @hidden */
  20228. AbstractMesh.prototype._rebuild = function () {
  20229. if (this._occlusionQuery) {
  20230. this._occlusionQuery = null;
  20231. }
  20232. if (this._edgesRenderer) {
  20233. this._edgesRenderer._rebuild();
  20234. }
  20235. if (!this.subMeshes) {
  20236. return;
  20237. }
  20238. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20239. var subMesh = _a[_i];
  20240. subMesh._rebuild();
  20241. }
  20242. };
  20243. /** @hidden */
  20244. AbstractMesh.prototype._resyncLightSources = function () {
  20245. this._lightSources.length = 0;
  20246. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20247. var light = _a[_i];
  20248. if (!light.isEnabled()) {
  20249. continue;
  20250. }
  20251. if (light.canAffectMesh(this)) {
  20252. this._lightSources.push(light);
  20253. }
  20254. }
  20255. this._markSubMeshesAsLightDirty();
  20256. };
  20257. /** @hidden */
  20258. AbstractMesh.prototype._resyncLighSource = function (light) {
  20259. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20260. var index = this._lightSources.indexOf(light);
  20261. if (index === -1) {
  20262. if (!isIn) {
  20263. return;
  20264. }
  20265. this._lightSources.push(light);
  20266. }
  20267. else {
  20268. if (isIn) {
  20269. return;
  20270. }
  20271. this._lightSources.splice(index, 1);
  20272. }
  20273. this._markSubMeshesAsLightDirty();
  20274. };
  20275. /** @hidden */
  20276. AbstractMesh.prototype._unBindEffect = function () {
  20277. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20278. var subMesh = _a[_i];
  20279. subMesh.setEffect(null);
  20280. }
  20281. };
  20282. /** @hidden */
  20283. AbstractMesh.prototype._removeLightSource = function (light) {
  20284. var index = this._lightSources.indexOf(light);
  20285. if (index === -1) {
  20286. return;
  20287. }
  20288. this._lightSources.splice(index, 1);
  20289. this._markSubMeshesAsLightDirty();
  20290. };
  20291. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20292. if (!this.subMeshes) {
  20293. return;
  20294. }
  20295. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20296. var subMesh = _a[_i];
  20297. if (subMesh._materialDefines) {
  20298. func(subMesh._materialDefines);
  20299. }
  20300. }
  20301. };
  20302. /** @hidden */
  20303. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20304. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20305. };
  20306. /** @hidden */
  20307. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20308. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20309. };
  20310. /** @hidden */
  20311. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20312. if (!this.subMeshes) {
  20313. return;
  20314. }
  20315. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20316. var subMesh = _a[_i];
  20317. var material = subMesh.getMaterial();
  20318. if (material) {
  20319. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20320. }
  20321. }
  20322. };
  20323. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20324. /**
  20325. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20326. */
  20327. get: function () {
  20328. return this._scaling;
  20329. },
  20330. set: function (newScaling) {
  20331. this._scaling = newScaling;
  20332. if (this.physicsImpostor) {
  20333. this.physicsImpostor.forceUpdate();
  20334. }
  20335. },
  20336. enumerable: true,
  20337. configurable: true
  20338. });
  20339. // Methods
  20340. /**
  20341. * Disables the mesh edge rendering mode
  20342. * @returns the currentAbstractMesh
  20343. */
  20344. AbstractMesh.prototype.disableEdgesRendering = function () {
  20345. if (this._edgesRenderer) {
  20346. this._edgesRenderer.dispose();
  20347. this._edgesRenderer = null;
  20348. }
  20349. return this;
  20350. };
  20351. /**
  20352. * Enables the edge rendering mode on the mesh.
  20353. * This mode makes the mesh edges visible
  20354. * @param epsilon defines the maximal distance between two angles to detect a face
  20355. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20356. * @returns the currentAbstractMesh
  20357. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20358. */
  20359. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20360. if (epsilon === void 0) { epsilon = 0.95; }
  20361. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20362. this.disableEdgesRendering();
  20363. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20364. return this;
  20365. };
  20366. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20367. /**
  20368. * Gets the edgesRenderer associated with the mesh
  20369. */
  20370. get: function () {
  20371. return this._edgesRenderer;
  20372. },
  20373. enumerable: true,
  20374. configurable: true
  20375. });
  20376. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20377. /**
  20378. * Returns true if the mesh is blocked. Implemented by child classes
  20379. */
  20380. get: function () {
  20381. return false;
  20382. },
  20383. enumerable: true,
  20384. configurable: true
  20385. });
  20386. /**
  20387. * Returns the mesh itself by default. Implemented by child classes
  20388. * @param camera defines the camera to use to pick the right LOD level
  20389. * @returns the currentAbstractMesh
  20390. */
  20391. AbstractMesh.prototype.getLOD = function (camera) {
  20392. return this;
  20393. };
  20394. /**
  20395. * Returns 0 by default. Implemented by child classes
  20396. * @returns an integer
  20397. */
  20398. AbstractMesh.prototype.getTotalVertices = function () {
  20399. return 0;
  20400. };
  20401. /**
  20402. * Returns null by default. Implemented by child classes
  20403. * @returns null
  20404. */
  20405. AbstractMesh.prototype.getIndices = function () {
  20406. return null;
  20407. };
  20408. /**
  20409. * Returns the array of the requested vertex data kind. Implemented by child classes
  20410. * @param kind defines the vertex data kind to use
  20411. * @returns null
  20412. */
  20413. AbstractMesh.prototype.getVerticesData = function (kind) {
  20414. return null;
  20415. };
  20416. /**
  20417. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20418. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20419. * Note that a new underlying VertexBuffer object is created each call.
  20420. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20421. * @param kind defines vertex data kind:
  20422. * * BABYLON.VertexBuffer.PositionKind
  20423. * * BABYLON.VertexBuffer.UVKind
  20424. * * BABYLON.VertexBuffer.UV2Kind
  20425. * * BABYLON.VertexBuffer.UV3Kind
  20426. * * BABYLON.VertexBuffer.UV4Kind
  20427. * * BABYLON.VertexBuffer.UV5Kind
  20428. * * BABYLON.VertexBuffer.UV6Kind
  20429. * * BABYLON.VertexBuffer.ColorKind
  20430. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20431. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20432. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20433. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20434. * @param data defines the data source
  20435. * @param updatable defines if the data must be flagged as updatable (or static)
  20436. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20437. * @returns the current mesh
  20438. */
  20439. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20440. return this;
  20441. };
  20442. /**
  20443. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20444. * If the mesh has no geometry, it is simply returned as it is.
  20445. * @param kind defines vertex data kind:
  20446. * * BABYLON.VertexBuffer.PositionKind
  20447. * * BABYLON.VertexBuffer.UVKind
  20448. * * BABYLON.VertexBuffer.UV2Kind
  20449. * * BABYLON.VertexBuffer.UV3Kind
  20450. * * BABYLON.VertexBuffer.UV4Kind
  20451. * * BABYLON.VertexBuffer.UV5Kind
  20452. * * BABYLON.VertexBuffer.UV6Kind
  20453. * * BABYLON.VertexBuffer.ColorKind
  20454. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20455. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20456. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20457. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20458. * @param data defines the data source
  20459. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20460. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20461. * @returns the current mesh
  20462. */
  20463. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20464. return this;
  20465. };
  20466. /**
  20467. * Sets the mesh indices,
  20468. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20469. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20470. * @param totalVertices Defines the total number of vertices
  20471. * @returns the current mesh
  20472. */
  20473. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20474. return this;
  20475. };
  20476. /**
  20477. * Gets a boolean indicating if specific vertex data is present
  20478. * @param kind defines the vertex data kind to use
  20479. * @returns true is data kind is present
  20480. */
  20481. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20482. return false;
  20483. };
  20484. /**
  20485. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20486. * @returns a BoundingInfo
  20487. */
  20488. AbstractMesh.prototype.getBoundingInfo = function () {
  20489. if (this._masterMesh) {
  20490. return this._masterMesh.getBoundingInfo();
  20491. }
  20492. if (!this._boundingInfo) {
  20493. // this._boundingInfo is being created here
  20494. this._updateBoundingInfo();
  20495. }
  20496. // cannot be null.
  20497. return this._boundingInfo;
  20498. };
  20499. /**
  20500. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20501. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20502. * @returns the current mesh
  20503. */
  20504. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20505. if (includeDescendants === void 0) { includeDescendants = true; }
  20506. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20507. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20508. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20509. if (maxDimension === 0) {
  20510. return this;
  20511. }
  20512. var scale = 1 / maxDimension;
  20513. this.scaling.scaleInPlace(scale);
  20514. return this;
  20515. };
  20516. /**
  20517. * Overwrite the current bounding info
  20518. * @param boundingInfo defines the new bounding info
  20519. * @returns the current mesh
  20520. */
  20521. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20522. this._boundingInfo = boundingInfo;
  20523. return this;
  20524. };
  20525. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20526. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20527. get: function () {
  20528. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20529. },
  20530. enumerable: true,
  20531. configurable: true
  20532. });
  20533. /** @hidden */
  20534. AbstractMesh.prototype._preActivate = function () {
  20535. };
  20536. /** @hidden */
  20537. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20538. };
  20539. /** @hidden */
  20540. AbstractMesh.prototype._activate = function (renderId) {
  20541. this._renderId = renderId;
  20542. };
  20543. /**
  20544. * Gets the current world matrix
  20545. * @returns a Matrix
  20546. */
  20547. AbstractMesh.prototype.getWorldMatrix = function () {
  20548. if (this._masterMesh) {
  20549. return this._masterMesh.getWorldMatrix();
  20550. }
  20551. return _super.prototype.getWorldMatrix.call(this);
  20552. };
  20553. /** @hidden */
  20554. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20555. if (this._masterMesh) {
  20556. return this._masterMesh._getWorldMatrixDeterminant();
  20557. }
  20558. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20559. };
  20560. // ================================== Point of View Movement =================================
  20561. /**
  20562. * Perform relative position change from the point of view of behind the front of the mesh.
  20563. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20564. * Supports definition of mesh facing forward or backward
  20565. * @param amountRight defines the distance on the right axis
  20566. * @param amountUp defines the distance on the up axis
  20567. * @param amountForward defines the distance on the forward axis
  20568. * @returns the current mesh
  20569. */
  20570. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20571. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20572. return this;
  20573. };
  20574. /**
  20575. * Calculate relative position change from the point of view of behind the front of the mesh.
  20576. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20577. * Supports definition of mesh facing forward or backward
  20578. * @param amountRight defines the distance on the right axis
  20579. * @param amountUp defines the distance on the up axis
  20580. * @param amountForward defines the distance on the forward axis
  20581. * @returns the new displacement vector
  20582. */
  20583. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20584. var rotMatrix = new BABYLON.Matrix();
  20585. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20586. rotQuaternion.toRotationMatrix(rotMatrix);
  20587. var translationDelta = BABYLON.Vector3.Zero();
  20588. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20589. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20590. return translationDelta;
  20591. };
  20592. // ================================== Point of View Rotation =================================
  20593. /**
  20594. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20595. * Supports definition of mesh facing forward or backward
  20596. * @param flipBack defines the flip
  20597. * @param twirlClockwise defines the twirl
  20598. * @param tiltRight defines the tilt
  20599. * @returns the current mesh
  20600. */
  20601. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20602. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20603. return this;
  20604. };
  20605. /**
  20606. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20607. * Supports definition of mesh facing forward or backward.
  20608. * @param flipBack defines the flip
  20609. * @param twirlClockwise defines the twirl
  20610. * @param tiltRight defines the tilt
  20611. * @returns the new rotation vector
  20612. */
  20613. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20614. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20615. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20616. };
  20617. /**
  20618. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20619. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20620. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20621. * @returns the new bounding vectors
  20622. */
  20623. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20624. if (includeDescendants === void 0) { includeDescendants = true; }
  20625. if (predicate === void 0) { predicate = null; }
  20626. // Ensures that all world matrix will be recomputed.
  20627. this.getScene().incrementRenderId();
  20628. this.computeWorldMatrix(true);
  20629. var min;
  20630. var max;
  20631. var boundingInfo = this.getBoundingInfo();
  20632. if (!this.subMeshes) {
  20633. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20634. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20635. }
  20636. else {
  20637. min = boundingInfo.boundingBox.minimumWorld;
  20638. max = boundingInfo.boundingBox.maximumWorld;
  20639. }
  20640. if (includeDescendants) {
  20641. var descendants = this.getDescendants(false);
  20642. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20643. var descendant = descendants_1[_i];
  20644. var childMesh = descendant;
  20645. childMesh.computeWorldMatrix(true);
  20646. // Filters meshes based on custom predicate function.
  20647. if (predicate && !predicate(childMesh)) {
  20648. continue;
  20649. }
  20650. //make sure we have the needed params to get mix and max
  20651. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20652. continue;
  20653. }
  20654. var childBoundingInfo = childMesh.getBoundingInfo();
  20655. var boundingBox = childBoundingInfo.boundingBox;
  20656. var minBox = boundingBox.minimumWorld;
  20657. var maxBox = boundingBox.maximumWorld;
  20658. BABYLON.Tools.CheckExtends(minBox, min, max);
  20659. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20660. }
  20661. }
  20662. return {
  20663. min: min,
  20664. max: max
  20665. };
  20666. };
  20667. /** @hidden */
  20668. AbstractMesh.prototype._updateBoundingInfo = function () {
  20669. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20670. this._boundingInfo.update(this.worldMatrixFromCache);
  20671. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20672. return this;
  20673. };
  20674. /** @hidden */
  20675. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20676. if (!this.subMeshes) {
  20677. return this;
  20678. }
  20679. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20680. var subMesh = this.subMeshes[subIndex];
  20681. if (!subMesh.IsGlobal) {
  20682. subMesh.updateBoundingInfo(matrix);
  20683. }
  20684. }
  20685. return this;
  20686. };
  20687. /** @hidden */
  20688. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20689. // Bounding info
  20690. this._updateBoundingInfo();
  20691. };
  20692. /**
  20693. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20694. * A mesh is in the frustum if its bounding box intersects the frustum
  20695. * @param frustumPlanes defines the frustum to test
  20696. * @returns true if the mesh is in the frustum planes
  20697. */
  20698. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20699. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20700. };
  20701. /**
  20702. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20703. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20704. * @param frustumPlanes defines the frustum to test
  20705. * @returns true if the mesh is completely in the frustum planes
  20706. */
  20707. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20708. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20709. };
  20710. /**
  20711. * True if the mesh intersects another mesh or a SolidParticle object
  20712. * @param mesh defines a target mesh or SolidParticle to test
  20713. * @param precise 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)
  20714. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20715. * @returns true if there is an intersection
  20716. */
  20717. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20718. if (precise === void 0) { precise = false; }
  20719. if (!this._boundingInfo || !mesh._boundingInfo) {
  20720. return false;
  20721. }
  20722. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20723. return true;
  20724. }
  20725. if (includeDescendants) {
  20726. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20727. var child = _a[_i];
  20728. if (child.intersectsMesh(mesh, precise, true)) {
  20729. return true;
  20730. }
  20731. }
  20732. }
  20733. return false;
  20734. };
  20735. /**
  20736. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20737. * @param point defines the point to test
  20738. * @returns true if there is an intersection
  20739. */
  20740. AbstractMesh.prototype.intersectsPoint = function (point) {
  20741. if (!this._boundingInfo) {
  20742. return false;
  20743. }
  20744. return this._boundingInfo.intersectsPoint(point);
  20745. };
  20746. /**
  20747. * Gets the current physics impostor
  20748. * @see http://doc.babylonjs.com/features/physics_engine
  20749. * @returns a physics impostor or null
  20750. */
  20751. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20752. return this.physicsImpostor;
  20753. };
  20754. /**
  20755. * Gets the position of the current mesh in camera space
  20756. * @param camera defines the camera to use
  20757. * @returns a position
  20758. */
  20759. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20760. if (camera === void 0) { camera = null; }
  20761. if (!camera) {
  20762. camera = this.getScene().activeCamera;
  20763. }
  20764. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20765. };
  20766. /**
  20767. * Returns the distance from the mesh to the active camera
  20768. * @param camera defines the camera to use
  20769. * @returns the distance
  20770. */
  20771. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20772. if (camera === void 0) { camera = null; }
  20773. if (!camera) {
  20774. camera = this.getScene().activeCamera;
  20775. }
  20776. return this.absolutePosition.subtract(camera.position).length();
  20777. };
  20778. /**
  20779. * Apply a physic impulse to the mesh
  20780. * @param force defines the force to apply
  20781. * @param contactPoint defines where to apply the force
  20782. * @returns the current mesh
  20783. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20784. */
  20785. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20786. if (!this.physicsImpostor) {
  20787. return this;
  20788. }
  20789. this.physicsImpostor.applyImpulse(force, contactPoint);
  20790. return this;
  20791. };
  20792. /**
  20793. * Creates a physic joint between two meshes
  20794. * @param otherMesh defines the other mesh to use
  20795. * @param pivot1 defines the pivot to use on this mesh
  20796. * @param pivot2 defines the pivot to use on the other mesh
  20797. * @param options defines additional options (can be plugin dependent)
  20798. * @returns the current mesh
  20799. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20800. */
  20801. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20802. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20803. return this;
  20804. }
  20805. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20806. mainPivot: pivot1,
  20807. connectedPivot: pivot2,
  20808. nativeParams: options
  20809. });
  20810. return this;
  20811. };
  20812. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20813. // Collisions
  20814. /**
  20815. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20816. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20817. */
  20818. get: function () {
  20819. return this._checkCollisions;
  20820. },
  20821. set: function (collisionEnabled) {
  20822. this._checkCollisions = collisionEnabled;
  20823. if (this.getScene().workerCollisions) {
  20824. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20825. }
  20826. },
  20827. enumerable: true,
  20828. configurable: true
  20829. });
  20830. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20831. /**
  20832. * Gets Collider object used to compute collisions (not physics)
  20833. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20834. */
  20835. get: function () {
  20836. return this._collider;
  20837. },
  20838. enumerable: true,
  20839. configurable: true
  20840. });
  20841. /**
  20842. * Move the mesh using collision engine
  20843. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20844. * @param displacement defines the requested displacement vector
  20845. * @returns the current mesh
  20846. */
  20847. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20848. var globalPosition = this.getAbsolutePosition();
  20849. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20850. if (!this._collider) {
  20851. this._collider = new BABYLON.Collider();
  20852. }
  20853. this._collider._radius = this.ellipsoid;
  20854. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20855. return this;
  20856. };
  20857. // Submeshes octree
  20858. /**
  20859. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20860. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20861. * @param maxCapacity defines the maximum size of each block (64 by default)
  20862. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20863. * @returns the new octree
  20864. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20865. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20866. */
  20867. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20868. if (maxCapacity === void 0) { maxCapacity = 64; }
  20869. if (maxDepth === void 0) { maxDepth = 2; }
  20870. if (!this._submeshesOctree) {
  20871. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20872. }
  20873. this.computeWorldMatrix(true);
  20874. var boundingInfo = this.getBoundingInfo();
  20875. // Update octree
  20876. var bbox = boundingInfo.boundingBox;
  20877. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20878. return this._submeshesOctree;
  20879. };
  20880. // Collisions
  20881. /** @hidden */
  20882. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20883. this._generatePointsArray();
  20884. if (!this._positions) {
  20885. return this;
  20886. }
  20887. // Transformation
  20888. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20889. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20890. subMesh._lastColliderWorldVertices = [];
  20891. subMesh._trianglePlanes = [];
  20892. var start = subMesh.verticesStart;
  20893. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20894. for (var i = start; i < end; i++) {
  20895. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20896. }
  20897. }
  20898. // Collide
  20899. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20900. if (collider.collisionFound) {
  20901. collider.collidedMesh = this;
  20902. }
  20903. return this;
  20904. };
  20905. /** @hidden */
  20906. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20907. var subMeshes;
  20908. var len;
  20909. // Octrees
  20910. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20911. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20912. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20913. len = intersections.length;
  20914. subMeshes = intersections.data;
  20915. }
  20916. else {
  20917. subMeshes = this.subMeshes;
  20918. len = subMeshes.length;
  20919. }
  20920. for (var index = 0; index < len; index++) {
  20921. var subMesh = subMeshes[index];
  20922. // Bounding test
  20923. if (len > 1 && !subMesh._checkCollision(collider))
  20924. continue;
  20925. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20926. }
  20927. return this;
  20928. };
  20929. /** @hidden */
  20930. AbstractMesh.prototype._checkCollision = function (collider) {
  20931. // Bounding box test
  20932. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20933. return this;
  20934. // Transformation matrix
  20935. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20936. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20937. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20938. return this;
  20939. };
  20940. // Picking
  20941. /** @hidden */
  20942. AbstractMesh.prototype._generatePointsArray = function () {
  20943. return false;
  20944. };
  20945. /**
  20946. * Checks if the passed Ray intersects with the mesh
  20947. * @param ray defines the ray to use
  20948. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20949. * @returns the picking info
  20950. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20951. */
  20952. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20953. var pickingInfo = new BABYLON.PickingInfo();
  20954. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20955. return pickingInfo;
  20956. }
  20957. if (!this._generatePointsArray()) {
  20958. return pickingInfo;
  20959. }
  20960. var intersectInfo = null;
  20961. // Octrees
  20962. var subMeshes;
  20963. var len;
  20964. if (this._submeshesOctree && this.useOctreeForPicking) {
  20965. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20966. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20967. len = intersections.length;
  20968. subMeshes = intersections.data;
  20969. }
  20970. else {
  20971. subMeshes = this.subMeshes;
  20972. len = subMeshes.length;
  20973. }
  20974. for (var index = 0; index < len; index++) {
  20975. var subMesh = subMeshes[index];
  20976. // Bounding test
  20977. if (len > 1 && !subMesh.canIntersects(ray))
  20978. continue;
  20979. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20980. if (currentIntersectInfo) {
  20981. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20982. intersectInfo = currentIntersectInfo;
  20983. intersectInfo.subMeshId = index;
  20984. if (fastCheck) {
  20985. break;
  20986. }
  20987. }
  20988. }
  20989. }
  20990. if (intersectInfo) {
  20991. // Get picked point
  20992. var world = this.getWorldMatrix();
  20993. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20994. var direction = ray.direction.clone();
  20995. direction = direction.scale(intersectInfo.distance);
  20996. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20997. var pickedPoint = worldOrigin.add(worldDirection);
  20998. // Return result
  20999. pickingInfo.hit = true;
  21000. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21001. pickingInfo.pickedPoint = pickedPoint;
  21002. pickingInfo.pickedMesh = this;
  21003. pickingInfo.bu = intersectInfo.bu || 0;
  21004. pickingInfo.bv = intersectInfo.bv || 0;
  21005. pickingInfo.faceId = intersectInfo.faceId;
  21006. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21007. return pickingInfo;
  21008. }
  21009. return pickingInfo;
  21010. };
  21011. /**
  21012. * Clones the current mesh
  21013. * @param name defines the mesh name
  21014. * @param newParent defines the new mesh parent
  21015. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21016. * @returns the new mesh
  21017. */
  21018. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21019. return null;
  21020. };
  21021. /**
  21022. * Disposes all the submeshes of the current meshnp
  21023. * @returns the current mesh
  21024. */
  21025. AbstractMesh.prototype.releaseSubMeshes = function () {
  21026. if (this.subMeshes) {
  21027. while (this.subMeshes.length) {
  21028. this.subMeshes[0].dispose();
  21029. }
  21030. }
  21031. else {
  21032. this.subMeshes = new Array();
  21033. }
  21034. return this;
  21035. };
  21036. /**
  21037. * Releases resources associated with this abstract mesh.
  21038. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21039. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21040. */
  21041. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21042. var _this = this;
  21043. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21044. var index;
  21045. // Smart Array Retainers.
  21046. this.getScene().freeActiveMeshes();
  21047. this.getScene().freeRenderingGroups();
  21048. // Action manager
  21049. if (this.actionManager !== undefined && this.actionManager !== null) {
  21050. this.actionManager.dispose();
  21051. this.actionManager = null;
  21052. }
  21053. // Skeleton
  21054. this._skeleton = null;
  21055. // Physics
  21056. if (this.physicsImpostor) {
  21057. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  21058. }
  21059. // Intersections in progress
  21060. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21061. var other = this._intersectionsInProgress[index];
  21062. var pos = other._intersectionsInProgress.indexOf(this);
  21063. other._intersectionsInProgress.splice(pos, 1);
  21064. }
  21065. this._intersectionsInProgress = [];
  21066. // Lights
  21067. var lights = this.getScene().lights;
  21068. lights.forEach(function (light) {
  21069. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21070. if (meshIndex !== -1) {
  21071. light.includedOnlyMeshes.splice(meshIndex, 1);
  21072. }
  21073. meshIndex = light.excludedMeshes.indexOf(_this);
  21074. if (meshIndex !== -1) {
  21075. light.excludedMeshes.splice(meshIndex, 1);
  21076. }
  21077. // Shadow generators
  21078. var generator = light.getShadowGenerator();
  21079. if (generator) {
  21080. var shadowMap = generator.getShadowMap();
  21081. if (shadowMap && shadowMap.renderList) {
  21082. meshIndex = shadowMap.renderList.indexOf(_this);
  21083. if (meshIndex !== -1) {
  21084. shadowMap.renderList.splice(meshIndex, 1);
  21085. }
  21086. }
  21087. }
  21088. });
  21089. // Edges
  21090. if (this._edgesRenderer) {
  21091. this._edgesRenderer.dispose();
  21092. this._edgesRenderer = null;
  21093. }
  21094. // SubMeshes
  21095. if (this.getClassName() !== "InstancedMesh") {
  21096. this.releaseSubMeshes();
  21097. }
  21098. // Octree
  21099. var sceneOctree = this.getScene().selectionOctree;
  21100. if (sceneOctree !== undefined && sceneOctree !== null) {
  21101. var index = sceneOctree.dynamicContent.indexOf(this);
  21102. if (index !== -1) {
  21103. sceneOctree.dynamicContent.splice(index, 1);
  21104. }
  21105. }
  21106. // Query
  21107. var engine = this.getScene().getEngine();
  21108. if (this._occlusionQuery) {
  21109. this._isOcclusionQueryInProgress = false;
  21110. engine.deleteQuery(this._occlusionQuery);
  21111. this._occlusionQuery = null;
  21112. }
  21113. // Engine
  21114. engine.wipeCaches();
  21115. // Remove from scene
  21116. this.getScene().removeMesh(this);
  21117. if (disposeMaterialAndTextures) {
  21118. if (this.material) {
  21119. this.material.dispose(false, true);
  21120. }
  21121. }
  21122. if (!doNotRecurse) {
  21123. // Particles
  21124. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21125. if (this.getScene().particleSystems[index].emitter === this) {
  21126. this.getScene().particleSystems[index].dispose();
  21127. index--;
  21128. }
  21129. }
  21130. }
  21131. // facet data
  21132. if (this._facetDataEnabled) {
  21133. this.disableFacetData();
  21134. }
  21135. this.onAfterWorldMatrixUpdateObservable.clear();
  21136. this.onCollideObservable.clear();
  21137. this.onCollisionPositionChangeObservable.clear();
  21138. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21139. };
  21140. /**
  21141. * Adds the passed mesh as a child to the current mesh
  21142. * @param mesh defines the child mesh
  21143. * @returns the current mesh
  21144. */
  21145. AbstractMesh.prototype.addChild = function (mesh) {
  21146. mesh.setParent(this);
  21147. return this;
  21148. };
  21149. /**
  21150. * Removes the passed mesh from the current mesh children list
  21151. * @param mesh defines the child mesh
  21152. * @returns the current mesh
  21153. */
  21154. AbstractMesh.prototype.removeChild = function (mesh) {
  21155. mesh.setParent(null);
  21156. return this;
  21157. };
  21158. // Facet data
  21159. /** @hidden */
  21160. AbstractMesh.prototype._initFacetData = function () {
  21161. if (!this._facetNormals) {
  21162. this._facetNormals = new Array();
  21163. }
  21164. if (!this._facetPositions) {
  21165. this._facetPositions = new Array();
  21166. }
  21167. if (!this._facetPartitioning) {
  21168. this._facetPartitioning = new Array();
  21169. }
  21170. this._facetNb = (this.getIndices().length / 3) | 0;
  21171. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21172. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21173. for (var f = 0; f < this._facetNb; f++) {
  21174. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21175. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21176. }
  21177. this._facetDataEnabled = true;
  21178. return this;
  21179. };
  21180. /**
  21181. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21182. * This method can be called within the render loop.
  21183. * 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
  21184. * @returns the current mesh
  21185. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21186. */
  21187. AbstractMesh.prototype.updateFacetData = function () {
  21188. if (!this._facetDataEnabled) {
  21189. this._initFacetData();
  21190. }
  21191. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21192. var indices = this.getIndices();
  21193. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21194. var bInfo = this.getBoundingInfo();
  21195. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21196. // init arrays, matrix and sort function on first call
  21197. this._facetDepthSortEnabled = true;
  21198. if (indices instanceof Uint16Array) {
  21199. this._depthSortedIndices = new Uint16Array(indices);
  21200. }
  21201. else if (indices instanceof Uint32Array) {
  21202. this._depthSortedIndices = new Uint32Array(indices);
  21203. }
  21204. else {
  21205. var needs32bits = false;
  21206. for (var i = 0; i < indices.length; i++) {
  21207. if (indices[i] > 65535) {
  21208. needs32bits = true;
  21209. break;
  21210. }
  21211. }
  21212. if (needs32bits) {
  21213. this._depthSortedIndices = new Uint32Array(indices);
  21214. }
  21215. else {
  21216. this._depthSortedIndices = new Uint16Array(indices);
  21217. }
  21218. }
  21219. this._facetDepthSortFunction = function (f1, f2) {
  21220. return (f2.sqDistance - f1.sqDistance);
  21221. };
  21222. if (!this._facetDepthSortFrom) {
  21223. var camera = this.getScene().activeCamera;
  21224. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21225. }
  21226. this._depthSortedFacets = [];
  21227. for (var f = 0; f < this._facetNb; f++) {
  21228. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21229. this._depthSortedFacets.push(depthSortedFacet);
  21230. }
  21231. this._invertedMatrix = BABYLON.Matrix.Identity();
  21232. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21233. }
  21234. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21235. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21236. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21237. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21238. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21239. this._subDiv.max = this._partitioningSubdivisions;
  21240. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21241. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21242. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21243. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21244. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21245. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21246. // set the parameters for ComputeNormals()
  21247. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21248. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21249. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21250. this._facetParameters.bInfo = bInfo;
  21251. this._facetParameters.bbSize = this._bbSize;
  21252. this._facetParameters.subDiv = this._subDiv;
  21253. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21254. this._facetParameters.depthSort = this._facetDepthSort;
  21255. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21256. this.computeWorldMatrix(true);
  21257. this._worldMatrix.invertToRef(this._invertedMatrix);
  21258. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21259. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21260. }
  21261. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21262. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21263. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21264. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21265. var l = (this._depthSortedIndices.length / 3) | 0;
  21266. for (var f = 0; f < l; f++) {
  21267. var sind = this._depthSortedFacets[f].ind;
  21268. this._depthSortedIndices[f * 3] = indices[sind];
  21269. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21270. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21271. }
  21272. this.updateIndices(this._depthSortedIndices);
  21273. }
  21274. return this;
  21275. };
  21276. /**
  21277. * Returns the facetLocalNormals array.
  21278. * The normals are expressed in the mesh local spac
  21279. * @returns an array of Vector3
  21280. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21281. */
  21282. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21283. if (!this._facetNormals) {
  21284. this.updateFacetData();
  21285. }
  21286. return this._facetNormals;
  21287. };
  21288. /**
  21289. * Returns the facetLocalPositions array.
  21290. * The facet positions are expressed in the mesh local space
  21291. * @returns an array of Vector3
  21292. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21293. */
  21294. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21295. if (!this._facetPositions) {
  21296. this.updateFacetData();
  21297. }
  21298. return this._facetPositions;
  21299. };
  21300. /**
  21301. * Returns the facetLocalPartioning array
  21302. * @returns an array of array of numbers
  21303. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21304. */
  21305. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21306. if (!this._facetPartitioning) {
  21307. this.updateFacetData();
  21308. }
  21309. return this._facetPartitioning;
  21310. };
  21311. /**
  21312. * Returns the i-th facet position in the world system.
  21313. * This method allocates a new Vector3 per call
  21314. * @param i defines the facet index
  21315. * @returns a new Vector3
  21316. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21317. */
  21318. AbstractMesh.prototype.getFacetPosition = function (i) {
  21319. var pos = BABYLON.Vector3.Zero();
  21320. this.getFacetPositionToRef(i, pos);
  21321. return pos;
  21322. };
  21323. /**
  21324. * Sets the reference Vector3 with the i-th facet position in the world system
  21325. * @param i defines the facet index
  21326. * @param ref defines the target vector
  21327. * @returns the current mesh
  21328. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21329. */
  21330. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21331. var localPos = (this.getFacetLocalPositions())[i];
  21332. var world = this.getWorldMatrix();
  21333. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21334. return this;
  21335. };
  21336. /**
  21337. * Returns the i-th facet normal in the world system.
  21338. * This method allocates a new Vector3 per call
  21339. * @param i defines the facet index
  21340. * @returns a new Vector3
  21341. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21342. */
  21343. AbstractMesh.prototype.getFacetNormal = function (i) {
  21344. var norm = BABYLON.Vector3.Zero();
  21345. this.getFacetNormalToRef(i, norm);
  21346. return norm;
  21347. };
  21348. /**
  21349. * Sets the reference Vector3 with the i-th facet normal in the world system
  21350. * @param i defines the facet index
  21351. * @param ref defines the target vector
  21352. * @returns the current mesh
  21353. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21354. */
  21355. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21356. var localNorm = (this.getFacetLocalNormals())[i];
  21357. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21358. return this;
  21359. };
  21360. /**
  21361. * 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)
  21362. * @param x defines x coordinate
  21363. * @param y defines y coordinate
  21364. * @param z defines z coordinate
  21365. * @returns the array of facet indexes
  21366. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21367. */
  21368. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21369. var bInfo = this.getBoundingInfo();
  21370. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21371. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21372. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21373. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21374. return null;
  21375. }
  21376. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21377. };
  21378. /**
  21379. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21380. * @param projected sets as the (x,y,z) world projection on the facet
  21381. * @param checkFace if 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
  21382. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  21383. * @param x defines x coordinate
  21384. * @param y defines y coordinate
  21385. * @param z defines z coordinate
  21386. * @returns the face index if found (or null instead)
  21387. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21388. */
  21389. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21390. if (checkFace === void 0) { checkFace = false; }
  21391. if (facing === void 0) { facing = true; }
  21392. var world = this.getWorldMatrix();
  21393. var invMat = BABYLON.Tmp.Matrix[5];
  21394. world.invertToRef(invMat);
  21395. var invVect = BABYLON.Tmp.Vector3[8];
  21396. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21397. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21398. if (projected) {
  21399. // tranform the local computed projected vector to world coordinates
  21400. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21401. }
  21402. return closest;
  21403. };
  21404. /**
  21405. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21406. * @param projected sets as the (x,y,z) local projection on the facet
  21407. * @param checkFace if 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
  21408. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  21409. * @param x defines x coordinate
  21410. * @param y defines y coordinate
  21411. * @param z defines z coordinate
  21412. * @returns the face index if found (or null instead)
  21413. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21414. */
  21415. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21416. if (checkFace === void 0) { checkFace = false; }
  21417. if (facing === void 0) { facing = true; }
  21418. var closest = null;
  21419. var tmpx = 0.0;
  21420. var tmpy = 0.0;
  21421. var tmpz = 0.0;
  21422. var d = 0.0; // tmp dot facet normal * facet position
  21423. var t0 = 0.0;
  21424. var projx = 0.0;
  21425. var projy = 0.0;
  21426. var projz = 0.0;
  21427. // Get all the facets in the same partitioning block than (x, y, z)
  21428. var facetPositions = this.getFacetLocalPositions();
  21429. var facetNormals = this.getFacetLocalNormals();
  21430. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21431. if (!facetsInBlock) {
  21432. return null;
  21433. }
  21434. // Get the closest facet to (x, y, z)
  21435. var shortest = Number.MAX_VALUE; // init distance vars
  21436. var tmpDistance = shortest;
  21437. var fib; // current facet in the block
  21438. var norm; // current facet normal
  21439. var p0; // current facet barycenter position
  21440. // loop on all the facets in the current partitioning block
  21441. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21442. fib = facetsInBlock[idx];
  21443. norm = facetNormals[fib];
  21444. p0 = facetPositions[fib];
  21445. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21446. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21447. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21448. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21449. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21450. projx = x + norm.x * t0;
  21451. projy = y + norm.y * t0;
  21452. projz = z + norm.z * t0;
  21453. tmpx = projx - x;
  21454. tmpy = projy - y;
  21455. tmpz = projz - z;
  21456. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21457. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21458. shortest = tmpDistance;
  21459. closest = fib;
  21460. if (projected) {
  21461. projected.x = projx;
  21462. projected.y = projy;
  21463. projected.z = projz;
  21464. }
  21465. }
  21466. }
  21467. }
  21468. return closest;
  21469. };
  21470. /**
  21471. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21472. * @returns the parameters
  21473. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21474. */
  21475. AbstractMesh.prototype.getFacetDataParameters = function () {
  21476. return this._facetParameters;
  21477. };
  21478. /**
  21479. * Disables the feature FacetData and frees the related memory
  21480. * @returns the current mesh
  21481. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21482. */
  21483. AbstractMesh.prototype.disableFacetData = function () {
  21484. if (this._facetDataEnabled) {
  21485. this._facetDataEnabled = false;
  21486. this._facetPositions = new Array();
  21487. this._facetNormals = new Array();
  21488. this._facetPartitioning = new Array();
  21489. this._facetParameters = null;
  21490. this._depthSortedIndices = new Uint32Array(0);
  21491. }
  21492. return this;
  21493. };
  21494. /**
  21495. * Updates the AbstractMesh indices array
  21496. * @param indices defines the data source
  21497. * @returns the current mesh
  21498. */
  21499. AbstractMesh.prototype.updateIndices = function (indices) {
  21500. return this;
  21501. };
  21502. /**
  21503. * Creates new normals data for the mesh
  21504. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21505. * @returns the current mesh
  21506. */
  21507. AbstractMesh.prototype.createNormals = function (updatable) {
  21508. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21509. var indices = this.getIndices();
  21510. var normals;
  21511. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21512. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21513. }
  21514. else {
  21515. normals = [];
  21516. }
  21517. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21518. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21519. return this;
  21520. };
  21521. /**
  21522. * Align the mesh with a normal
  21523. * @param normal defines the normal to use
  21524. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21525. * @returns the current mesh
  21526. */
  21527. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21528. if (!upDirection) {
  21529. upDirection = BABYLON.Axis.Y;
  21530. }
  21531. var axisX = BABYLON.Tmp.Vector3[0];
  21532. var axisZ = BABYLON.Tmp.Vector3[1];
  21533. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21534. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21535. if (this.rotationQuaternion) {
  21536. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21537. }
  21538. else {
  21539. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21540. }
  21541. return this;
  21542. };
  21543. /** @hidden */
  21544. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21545. var engine = this.getEngine();
  21546. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21547. this._isOccluded = false;
  21548. return;
  21549. }
  21550. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21551. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21552. if (isOcclusionQueryAvailable) {
  21553. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21554. this._isOcclusionQueryInProgress = false;
  21555. this._occlusionInternalRetryCounter = 0;
  21556. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21557. }
  21558. else {
  21559. this._occlusionInternalRetryCounter++;
  21560. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21561. this._isOcclusionQueryInProgress = false;
  21562. this._occlusionInternalRetryCounter = 0;
  21563. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21564. // if strict continue the last state of the object.
  21565. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21566. }
  21567. else {
  21568. return;
  21569. }
  21570. }
  21571. }
  21572. var scene = this.getScene();
  21573. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21574. if (!this._occlusionQuery) {
  21575. this._occlusionQuery = engine.createQuery();
  21576. }
  21577. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21578. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21579. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21580. this._isOcclusionQueryInProgress = true;
  21581. };
  21582. /** No occlusion */
  21583. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21584. /** Occlusion set to optimisitic */
  21585. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21586. /** Occlusion set to strict */
  21587. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21588. /** Use an accurante occlusion algorithm */
  21589. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21590. /** Use a conservative occlusion algorithm */
  21591. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21592. return AbstractMesh;
  21593. }(BABYLON.TransformNode));
  21594. BABYLON.AbstractMesh = AbstractMesh;
  21595. })(BABYLON || (BABYLON = {}));
  21596. //# sourceMappingURL=babylon.abstractMesh.js.map
  21597. var BABYLON;
  21598. (function (BABYLON) {
  21599. /**
  21600. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21601. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21602. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  21603. */
  21604. var Light = /** @class */ (function (_super) {
  21605. __extends(Light, _super);
  21606. /**
  21607. * Creates a Light object in the scene.
  21608. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21609. * @param name The firendly name of the light
  21610. * @param scene The scene the light belongs too
  21611. */
  21612. function Light(name, scene) {
  21613. var _this = _super.call(this, name, scene) || this;
  21614. /**
  21615. * Diffuse gives the basic color to an object.
  21616. */
  21617. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21618. /**
  21619. * Specular produces a highlight color on an object.
  21620. * Note: This is note affecting PBR materials.
  21621. */
  21622. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21623. /**
  21624. * Strength of the light.
  21625. * Note: By default it is define in the framework own unit.
  21626. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21627. */
  21628. _this.intensity = 1.0;
  21629. /**
  21630. * Defines how far from the source the light is impacting in scene units.
  21631. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21632. */
  21633. _this.range = Number.MAX_VALUE;
  21634. /**
  21635. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21636. * of light.
  21637. */
  21638. _this._photometricScale = 1.0;
  21639. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21640. _this._radius = 0.00001;
  21641. /**
  21642. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21643. * exceeding the number allowed of the materials.
  21644. */
  21645. _this.renderPriority = 0;
  21646. _this._shadowEnabled = true;
  21647. _this._excludeWithLayerMask = 0;
  21648. _this._includeOnlyWithLayerMask = 0;
  21649. _this._lightmapMode = 0;
  21650. /**
  21651. * @hidden Internal use only.
  21652. */
  21653. _this._excludedMeshesIds = new Array();
  21654. /**
  21655. * @hidden Internal use only.
  21656. */
  21657. _this._includedOnlyMeshesIds = new Array();
  21658. _this.getScene().addLight(_this);
  21659. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21660. _this._buildUniformLayout();
  21661. _this.includedOnlyMeshes = new Array();
  21662. _this.excludedMeshes = new Array();
  21663. _this._resyncMeshes();
  21664. return _this;
  21665. }
  21666. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21667. /**
  21668. * If every light affecting the material is in this lightmapMode,
  21669. * material.lightmapTexture adds or multiplies
  21670. * (depends on material.useLightmapAsShadowmap)
  21671. * after every other light calculations.
  21672. */
  21673. get: function () {
  21674. return Light._LIGHTMAP_DEFAULT;
  21675. },
  21676. enumerable: true,
  21677. configurable: true
  21678. });
  21679. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21680. /**
  21681. * material.lightmapTexture as only diffuse lighting from this light
  21682. * adds only specular lighting from this light
  21683. * adds dynamic shadows
  21684. */
  21685. get: function () {
  21686. return Light._LIGHTMAP_SPECULAR;
  21687. },
  21688. enumerable: true,
  21689. configurable: true
  21690. });
  21691. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21692. /**
  21693. * material.lightmapTexture as only lighting
  21694. * no light calculation from this light
  21695. * only adds dynamic shadows from this light
  21696. */
  21697. get: function () {
  21698. return Light._LIGHTMAP_SHADOWSONLY;
  21699. },
  21700. enumerable: true,
  21701. configurable: true
  21702. });
  21703. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21704. /**
  21705. * Each light type uses the default quantity according to its type:
  21706. * point/spot lights use luminous intensity
  21707. * directional lights use illuminance
  21708. */
  21709. get: function () {
  21710. return Light._INTENSITYMODE_AUTOMATIC;
  21711. },
  21712. enumerable: true,
  21713. configurable: true
  21714. });
  21715. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21716. /**
  21717. * lumen (lm)
  21718. */
  21719. get: function () {
  21720. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21721. },
  21722. enumerable: true,
  21723. configurable: true
  21724. });
  21725. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21726. /**
  21727. * candela (lm/sr)
  21728. */
  21729. get: function () {
  21730. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21731. },
  21732. enumerable: true,
  21733. configurable: true
  21734. });
  21735. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21736. /**
  21737. * lux (lm/m^2)
  21738. */
  21739. get: function () {
  21740. return Light._INTENSITYMODE_ILLUMINANCE;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21746. /**
  21747. * nit (cd/m^2)
  21748. */
  21749. get: function () {
  21750. return Light._INTENSITYMODE_LUMINANCE;
  21751. },
  21752. enumerable: true,
  21753. configurable: true
  21754. });
  21755. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21756. /**
  21757. * Light type const id of the point light.
  21758. */
  21759. get: function () {
  21760. return Light._LIGHTTYPEID_POINTLIGHT;
  21761. },
  21762. enumerable: true,
  21763. configurable: true
  21764. });
  21765. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21766. /**
  21767. * Light type const id of the directional light.
  21768. */
  21769. get: function () {
  21770. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21771. },
  21772. enumerable: true,
  21773. configurable: true
  21774. });
  21775. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21776. /**
  21777. * Light type const id of the spot light.
  21778. */
  21779. get: function () {
  21780. return Light._LIGHTTYPEID_SPOTLIGHT;
  21781. },
  21782. enumerable: true,
  21783. configurable: true
  21784. });
  21785. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21786. /**
  21787. * Light type const id of the hemispheric light.
  21788. */
  21789. get: function () {
  21790. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21791. },
  21792. enumerable: true,
  21793. configurable: true
  21794. });
  21795. Object.defineProperty(Light.prototype, "intensityMode", {
  21796. /**
  21797. * Gets the photometric scale used to interpret the intensity.
  21798. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21799. */
  21800. get: function () {
  21801. return this._intensityMode;
  21802. },
  21803. /**
  21804. * Sets the photometric scale used to interpret the intensity.
  21805. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21806. */
  21807. set: function (value) {
  21808. this._intensityMode = value;
  21809. this._computePhotometricScale();
  21810. },
  21811. enumerable: true,
  21812. configurable: true
  21813. });
  21814. ;
  21815. ;
  21816. Object.defineProperty(Light.prototype, "radius", {
  21817. /**
  21818. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21819. */
  21820. get: function () {
  21821. return this._radius;
  21822. },
  21823. /**
  21824. * sets the light radius used by PBR Materials to simulate soft area lights.
  21825. */
  21826. set: function (value) {
  21827. this._radius = value;
  21828. this._computePhotometricScale();
  21829. },
  21830. enumerable: true,
  21831. configurable: true
  21832. });
  21833. ;
  21834. ;
  21835. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21836. /**
  21837. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21838. * the current shadow generator.
  21839. */
  21840. get: function () {
  21841. return this._shadowEnabled;
  21842. },
  21843. /**
  21844. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21845. * the current shadow generator.
  21846. */
  21847. set: function (value) {
  21848. if (this._shadowEnabled === value) {
  21849. return;
  21850. }
  21851. this._shadowEnabled = value;
  21852. this._markMeshesAsLightDirty();
  21853. },
  21854. enumerable: true,
  21855. configurable: true
  21856. });
  21857. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21858. /**
  21859. * Gets the only meshes impacted by this light.
  21860. */
  21861. get: function () {
  21862. return this._includedOnlyMeshes;
  21863. },
  21864. /**
  21865. * Sets the only meshes impacted by this light.
  21866. */
  21867. set: function (value) {
  21868. this._includedOnlyMeshes = value;
  21869. this._hookArrayForIncludedOnly(value);
  21870. },
  21871. enumerable: true,
  21872. configurable: true
  21873. });
  21874. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21875. /**
  21876. * Gets the meshes not impacted by this light.
  21877. */
  21878. get: function () {
  21879. return this._excludedMeshes;
  21880. },
  21881. /**
  21882. * Sets the meshes not impacted by this light.
  21883. */
  21884. set: function (value) {
  21885. this._excludedMeshes = value;
  21886. this._hookArrayForExcluded(value);
  21887. },
  21888. enumerable: true,
  21889. configurable: true
  21890. });
  21891. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21892. /**
  21893. * Gets the layer id use to find what meshes are not impacted by the light.
  21894. * Inactive if 0
  21895. */
  21896. get: function () {
  21897. return this._excludeWithLayerMask;
  21898. },
  21899. /**
  21900. * Sets the layer id use to find what meshes are not impacted by the light.
  21901. * Inactive if 0
  21902. */
  21903. set: function (value) {
  21904. this._excludeWithLayerMask = value;
  21905. this._resyncMeshes();
  21906. },
  21907. enumerable: true,
  21908. configurable: true
  21909. });
  21910. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21911. /**
  21912. * Gets the layer id use to find what meshes are impacted by the light.
  21913. * Inactive if 0
  21914. */
  21915. get: function () {
  21916. return this._includeOnlyWithLayerMask;
  21917. },
  21918. /**
  21919. * Sets the layer id use to find what meshes are impacted by the light.
  21920. * Inactive if 0
  21921. */
  21922. set: function (value) {
  21923. this._includeOnlyWithLayerMask = value;
  21924. this._resyncMeshes();
  21925. },
  21926. enumerable: true,
  21927. configurable: true
  21928. });
  21929. Object.defineProperty(Light.prototype, "lightmapMode", {
  21930. /**
  21931. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21932. */
  21933. get: function () {
  21934. return this._lightmapMode;
  21935. },
  21936. /**
  21937. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21938. */
  21939. set: function (value) {
  21940. if (this._lightmapMode === value) {
  21941. return;
  21942. }
  21943. this._lightmapMode = value;
  21944. this._markMeshesAsLightDirty();
  21945. },
  21946. enumerable: true,
  21947. configurable: true
  21948. });
  21949. /**
  21950. * Returns the string "Light".
  21951. * @returns the class name
  21952. */
  21953. Light.prototype.getClassName = function () {
  21954. return "Light";
  21955. };
  21956. /**
  21957. * Converts the light information to a readable string for debug purpose.
  21958. * @param fullDetails Supports for multiple levels of logging within scene loading
  21959. * @returns the human readable light info
  21960. */
  21961. Light.prototype.toString = function (fullDetails) {
  21962. var ret = "Name: " + this.name;
  21963. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21964. if (this.animations) {
  21965. for (var i = 0; i < this.animations.length; i++) {
  21966. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21967. }
  21968. }
  21969. if (fullDetails) {
  21970. }
  21971. return ret;
  21972. };
  21973. /**
  21974. * Set the enabled state of this node.
  21975. * @param value - the new enabled state
  21976. */
  21977. Light.prototype.setEnabled = function (value) {
  21978. _super.prototype.setEnabled.call(this, value);
  21979. this._resyncMeshes();
  21980. };
  21981. /**
  21982. * Returns the Light associated shadow generator if any.
  21983. * @return the associated shadow generator.
  21984. */
  21985. Light.prototype.getShadowGenerator = function () {
  21986. return this._shadowGenerator;
  21987. };
  21988. /**
  21989. * Returns a Vector3, the absolute light position in the World.
  21990. * @returns the world space position of the light
  21991. */
  21992. Light.prototype.getAbsolutePosition = function () {
  21993. return BABYLON.Vector3.Zero();
  21994. };
  21995. /**
  21996. * Specifies if the light will affect the passed mesh.
  21997. * @param mesh The mesh to test against the light
  21998. * @return true the mesh is affected otherwise, false.
  21999. */
  22000. Light.prototype.canAffectMesh = function (mesh) {
  22001. if (!mesh) {
  22002. return true;
  22003. }
  22004. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22005. return false;
  22006. }
  22007. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22008. return false;
  22009. }
  22010. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22011. return false;
  22012. }
  22013. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22014. return false;
  22015. }
  22016. return true;
  22017. };
  22018. /**
  22019. * Computes and Returns the light World matrix.
  22020. * @returns the world matrix
  22021. */
  22022. Light.prototype.getWorldMatrix = function () {
  22023. this._currentRenderId = this.getScene().getRenderId();
  22024. this._childRenderId = this._currentRenderId;
  22025. var worldMatrix = this._getWorldMatrix();
  22026. if (this.parent && this.parent.getWorldMatrix) {
  22027. if (!this._parentedWorldMatrix) {
  22028. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  22029. }
  22030. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  22031. this._markSyncedWithParent();
  22032. return this._parentedWorldMatrix;
  22033. }
  22034. return worldMatrix;
  22035. };
  22036. /**
  22037. * Sort function to order lights for rendering.
  22038. * @param a First Light object to compare to second.
  22039. * @param b Second Light object to compare first.
  22040. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22041. */
  22042. Light.CompareLightsPriority = function (a, b) {
  22043. //shadow-casting lights have priority over non-shadow-casting lights
  22044. //the renderPrioirty is a secondary sort criterion
  22045. if (a.shadowEnabled !== b.shadowEnabled) {
  22046. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22047. }
  22048. return b.renderPriority - a.renderPriority;
  22049. };
  22050. /**
  22051. * Releases resources associated with this node.
  22052. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22053. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22054. */
  22055. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22056. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22057. if (this._shadowGenerator) {
  22058. this._shadowGenerator.dispose();
  22059. this._shadowGenerator = null;
  22060. }
  22061. // Animations
  22062. this.getScene().stopAnimation(this);
  22063. // Remove from meshes
  22064. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22065. var mesh = _a[_i];
  22066. mesh._removeLightSource(this);
  22067. }
  22068. this._uniformBuffer.dispose();
  22069. // Remove from scene
  22070. this.getScene().removeLight(this);
  22071. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22072. };
  22073. /**
  22074. * Returns the light type ID (integer).
  22075. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22076. */
  22077. Light.prototype.getTypeID = function () {
  22078. return 0;
  22079. };
  22080. /**
  22081. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22082. * @returns the scaled intensity in intensity mode unit
  22083. */
  22084. Light.prototype.getScaledIntensity = function () {
  22085. return this._photometricScale * this.intensity;
  22086. };
  22087. /**
  22088. * Returns a new Light object, named "name", from the current one.
  22089. * @param name The name of the cloned light
  22090. * @returns the new created light
  22091. */
  22092. Light.prototype.clone = function (name) {
  22093. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22094. if (!constructor) {
  22095. return null;
  22096. }
  22097. return BABYLON.SerializationHelper.Clone(constructor, this);
  22098. };
  22099. /**
  22100. * Serializes the current light into a Serialization object.
  22101. * @returns the serialized object.
  22102. */
  22103. Light.prototype.serialize = function () {
  22104. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22105. // Type
  22106. serializationObject.type = this.getTypeID();
  22107. // Parent
  22108. if (this.parent) {
  22109. serializationObject.parentId = this.parent.id;
  22110. }
  22111. // Inclusion / exclusions
  22112. if (this.excludedMeshes.length > 0) {
  22113. serializationObject.excludedMeshesIds = [];
  22114. this.excludedMeshes.forEach(function (mesh) {
  22115. serializationObject.excludedMeshesIds.push(mesh.id);
  22116. });
  22117. }
  22118. if (this.includedOnlyMeshes.length > 0) {
  22119. serializationObject.includedOnlyMeshesIds = [];
  22120. this.includedOnlyMeshes.forEach(function (mesh) {
  22121. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22122. });
  22123. }
  22124. // Animations
  22125. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22126. serializationObject.ranges = this.serializeAnimationRanges();
  22127. return serializationObject;
  22128. };
  22129. /**
  22130. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22131. * This new light is named "name" and added to the passed scene.
  22132. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22133. * @param name The friendly name of the light
  22134. * @param scene The scene the new light will belong to
  22135. * @returns the constructor function
  22136. */
  22137. Light.GetConstructorFromName = function (type, name, scene) {
  22138. switch (type) {
  22139. case 0:
  22140. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22141. case 1:
  22142. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22143. case 2:
  22144. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22145. case 3:
  22146. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22147. }
  22148. return null;
  22149. };
  22150. /**
  22151. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22152. * @param parsedLight The JSON representation of the light
  22153. * @param scene The scene to create the parsed light in
  22154. * @returns the created light after parsing
  22155. */
  22156. Light.Parse = function (parsedLight, scene) {
  22157. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22158. if (!constructor) {
  22159. return null;
  22160. }
  22161. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22162. // Inclusion / exclusions
  22163. if (parsedLight.excludedMeshesIds) {
  22164. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22165. }
  22166. if (parsedLight.includedOnlyMeshesIds) {
  22167. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22168. }
  22169. // Parent
  22170. if (parsedLight.parentId) {
  22171. light._waitingParentId = parsedLight.parentId;
  22172. }
  22173. // Animations
  22174. if (parsedLight.animations) {
  22175. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22176. var parsedAnimation = parsedLight.animations[animationIndex];
  22177. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22178. }
  22179. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22180. }
  22181. if (parsedLight.autoAnimate) {
  22182. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22183. }
  22184. return light;
  22185. };
  22186. Light.prototype._hookArrayForExcluded = function (array) {
  22187. var _this = this;
  22188. var oldPush = array.push;
  22189. array.push = function () {
  22190. var items = [];
  22191. for (var _i = 0; _i < arguments.length; _i++) {
  22192. items[_i] = arguments[_i];
  22193. }
  22194. var result = oldPush.apply(array, items);
  22195. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22196. var item = items_1[_a];
  22197. item._resyncLighSource(_this);
  22198. }
  22199. return result;
  22200. };
  22201. var oldSplice = array.splice;
  22202. array.splice = function (index, deleteCount) {
  22203. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22204. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22205. var item = deleted_1[_i];
  22206. item._resyncLighSource(_this);
  22207. }
  22208. return deleted;
  22209. };
  22210. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22211. var item = array_1[_i];
  22212. item._resyncLighSource(this);
  22213. }
  22214. };
  22215. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22216. var _this = this;
  22217. var oldPush = array.push;
  22218. array.push = function () {
  22219. var items = [];
  22220. for (var _i = 0; _i < arguments.length; _i++) {
  22221. items[_i] = arguments[_i];
  22222. }
  22223. var result = oldPush.apply(array, items);
  22224. _this._resyncMeshes();
  22225. return result;
  22226. };
  22227. var oldSplice = array.splice;
  22228. array.splice = function (index, deleteCount) {
  22229. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22230. _this._resyncMeshes();
  22231. return deleted;
  22232. };
  22233. this._resyncMeshes();
  22234. };
  22235. Light.prototype._resyncMeshes = function () {
  22236. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22237. var mesh = _a[_i];
  22238. mesh._resyncLighSource(this);
  22239. }
  22240. };
  22241. /**
  22242. * Forces the meshes to update their light related information in their rendering used effects
  22243. * @hidden Internal Use Only
  22244. */
  22245. Light.prototype._markMeshesAsLightDirty = function () {
  22246. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22247. var mesh = _a[_i];
  22248. if (mesh._lightSources.indexOf(this) !== -1) {
  22249. mesh._markSubMeshesAsLightDirty();
  22250. }
  22251. }
  22252. };
  22253. /**
  22254. * Recomputes the cached photometric scale if needed.
  22255. */
  22256. Light.prototype._computePhotometricScale = function () {
  22257. this._photometricScale = this._getPhotometricScale();
  22258. this.getScene().resetCachedMaterial();
  22259. };
  22260. /**
  22261. * Returns the Photometric Scale according to the light type and intensity mode.
  22262. */
  22263. Light.prototype._getPhotometricScale = function () {
  22264. var photometricScale = 0.0;
  22265. var lightTypeID = this.getTypeID();
  22266. //get photometric mode
  22267. var photometricMode = this.intensityMode;
  22268. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22269. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22270. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22271. }
  22272. else {
  22273. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22274. }
  22275. }
  22276. //compute photometric scale
  22277. switch (lightTypeID) {
  22278. case Light.LIGHTTYPEID_POINTLIGHT:
  22279. case Light.LIGHTTYPEID_SPOTLIGHT:
  22280. switch (photometricMode) {
  22281. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22282. photometricScale = 1.0 / (4.0 * Math.PI);
  22283. break;
  22284. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22285. photometricScale = 1.0;
  22286. break;
  22287. case Light.INTENSITYMODE_LUMINANCE:
  22288. photometricScale = this.radius * this.radius;
  22289. break;
  22290. }
  22291. break;
  22292. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22293. switch (photometricMode) {
  22294. case Light.INTENSITYMODE_ILLUMINANCE:
  22295. photometricScale = 1.0;
  22296. break;
  22297. case Light.INTENSITYMODE_LUMINANCE:
  22298. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22299. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22300. var apexAngleRadians = this.radius;
  22301. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22302. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22303. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22304. photometricScale = solidAngle;
  22305. break;
  22306. }
  22307. break;
  22308. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22309. // No fall off in hemisperic light.
  22310. photometricScale = 1.0;
  22311. break;
  22312. }
  22313. return photometricScale;
  22314. };
  22315. /**
  22316. * Reorder the light in the scene according to their defined priority.
  22317. * @hidden Internal Use Only
  22318. */
  22319. Light.prototype._reorderLightsInScene = function () {
  22320. var scene = this.getScene();
  22321. if (this._renderPriority != 0) {
  22322. scene.requireLightSorting = true;
  22323. }
  22324. this.getScene().sortLightsByPriority();
  22325. };
  22326. //lightmapMode Consts
  22327. Light._LIGHTMAP_DEFAULT = 0;
  22328. Light._LIGHTMAP_SPECULAR = 1;
  22329. Light._LIGHTMAP_SHADOWSONLY = 2;
  22330. // Intensity Mode Consts
  22331. Light._INTENSITYMODE_AUTOMATIC = 0;
  22332. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22333. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22334. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22335. Light._INTENSITYMODE_LUMINANCE = 4;
  22336. // Light types ids const.
  22337. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22338. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22339. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22340. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22341. __decorate([
  22342. BABYLON.serializeAsColor3()
  22343. ], Light.prototype, "diffuse", void 0);
  22344. __decorate([
  22345. BABYLON.serializeAsColor3()
  22346. ], Light.prototype, "specular", void 0);
  22347. __decorate([
  22348. BABYLON.serialize()
  22349. ], Light.prototype, "intensity", void 0);
  22350. __decorate([
  22351. BABYLON.serialize()
  22352. ], Light.prototype, "range", void 0);
  22353. __decorate([
  22354. BABYLON.serialize()
  22355. ], Light.prototype, "intensityMode", null);
  22356. __decorate([
  22357. BABYLON.serialize()
  22358. ], Light.prototype, "radius", null);
  22359. __decorate([
  22360. BABYLON.serialize()
  22361. ], Light.prototype, "_renderPriority", void 0);
  22362. __decorate([
  22363. BABYLON.expandToProperty("_reorderLightsInScene")
  22364. ], Light.prototype, "renderPriority", void 0);
  22365. __decorate([
  22366. BABYLON.serialize("shadowEnabled")
  22367. ], Light.prototype, "_shadowEnabled", void 0);
  22368. __decorate([
  22369. BABYLON.serialize("excludeWithLayerMask")
  22370. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22371. __decorate([
  22372. BABYLON.serialize("includeOnlyWithLayerMask")
  22373. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22374. __decorate([
  22375. BABYLON.serialize("lightmapMode")
  22376. ], Light.prototype, "_lightmapMode", void 0);
  22377. return Light;
  22378. }(BABYLON.Node));
  22379. BABYLON.Light = Light;
  22380. })(BABYLON || (BABYLON = {}));
  22381. //# sourceMappingURL=babylon.light.js.map
  22382. var BABYLON;
  22383. (function (BABYLON) {
  22384. var Camera = /** @class */ (function (_super) {
  22385. __extends(Camera, _super);
  22386. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22387. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22388. var _this = _super.call(this, name, scene) || this;
  22389. /**
  22390. * The vector the camera should consider as up.
  22391. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22392. */
  22393. _this.upVector = BABYLON.Vector3.Up();
  22394. _this.orthoLeft = null;
  22395. _this.orthoRight = null;
  22396. _this.orthoBottom = null;
  22397. _this.orthoTop = null;
  22398. /**
  22399. * FOV is set in Radians. (default is 0.8)
  22400. */
  22401. _this.fov = 0.8;
  22402. _this.minZ = 1;
  22403. _this.maxZ = 10000.0;
  22404. _this.inertia = 0.9;
  22405. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22406. _this.isIntermediate = false;
  22407. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22408. /**
  22409. * Restricts the camera to viewing objects with the same layerMask.
  22410. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22411. */
  22412. _this.layerMask = 0x0FFFFFFF;
  22413. /**
  22414. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22415. */
  22416. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22417. // Camera rig members
  22418. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22419. _this._rigCameras = new Array();
  22420. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22421. _this._skipRendering = false;
  22422. _this.customRenderTargets = new Array();
  22423. // Observables
  22424. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22425. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22426. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22427. _this.onRestoreStateObservable = new BABYLON.Observable();
  22428. // Cache
  22429. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22430. _this._projectionMatrix = new BABYLON.Matrix();
  22431. _this._doNotComputeProjectionMatrix = false;
  22432. _this._worldMatrix = BABYLON.Matrix.Identity();
  22433. _this._postProcesses = new Array();
  22434. _this._transformMatrix = BABYLON.Matrix.Zero();
  22435. _this._activeMeshes = new BABYLON.SmartArray(256);
  22436. _this._globalPosition = BABYLON.Vector3.Zero();
  22437. _this._refreshFrustumPlanes = true;
  22438. _this.getScene().addCamera(_this);
  22439. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22440. _this.getScene().activeCamera = _this;
  22441. }
  22442. _this.position = position;
  22443. return _this;
  22444. }
  22445. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22446. get: function () {
  22447. return Camera._PERSPECTIVE_CAMERA;
  22448. },
  22449. enumerable: true,
  22450. configurable: true
  22451. });
  22452. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22453. get: function () {
  22454. return Camera._ORTHOGRAPHIC_CAMERA;
  22455. },
  22456. enumerable: true,
  22457. configurable: true
  22458. });
  22459. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22460. /**
  22461. * This is the default FOV mode for perspective cameras.
  22462. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22463. *
  22464. */
  22465. get: function () {
  22466. return Camera._FOVMODE_VERTICAL_FIXED;
  22467. },
  22468. enumerable: true,
  22469. configurable: true
  22470. });
  22471. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22472. /**
  22473. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22474. *
  22475. */
  22476. get: function () {
  22477. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22478. },
  22479. enumerable: true,
  22480. configurable: true
  22481. });
  22482. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22483. get: function () {
  22484. return Camera._RIG_MODE_NONE;
  22485. },
  22486. enumerable: true,
  22487. configurable: true
  22488. });
  22489. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22490. get: function () {
  22491. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22492. },
  22493. enumerable: true,
  22494. configurable: true
  22495. });
  22496. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22497. get: function () {
  22498. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22499. },
  22500. enumerable: true,
  22501. configurable: true
  22502. });
  22503. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22504. get: function () {
  22505. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22506. },
  22507. enumerable: true,
  22508. configurable: true
  22509. });
  22510. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22511. get: function () {
  22512. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22513. },
  22514. enumerable: true,
  22515. configurable: true
  22516. });
  22517. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22518. get: function () {
  22519. return Camera._RIG_MODE_VR;
  22520. },
  22521. enumerable: true,
  22522. configurable: true
  22523. });
  22524. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22525. get: function () {
  22526. return Camera._RIG_MODE_WEBVR;
  22527. },
  22528. enumerable: true,
  22529. configurable: true
  22530. });
  22531. /**
  22532. * Store current camera state (fov, position, etc..)
  22533. */
  22534. Camera.prototype.storeState = function () {
  22535. this._stateStored = true;
  22536. this._storedFov = this.fov;
  22537. return this;
  22538. };
  22539. /**
  22540. * Restores the camera state values if it has been stored. You must call storeState() first
  22541. */
  22542. Camera.prototype._restoreStateValues = function () {
  22543. if (!this._stateStored) {
  22544. return false;
  22545. }
  22546. this.fov = this._storedFov;
  22547. return true;
  22548. };
  22549. /**
  22550. * Restored camera state. You must call storeState() first
  22551. */
  22552. Camera.prototype.restoreState = function () {
  22553. if (this._restoreStateValues()) {
  22554. this.onRestoreStateObservable.notifyObservers(this);
  22555. return true;
  22556. }
  22557. return false;
  22558. };
  22559. Camera.prototype.getClassName = function () {
  22560. return "Camera";
  22561. };
  22562. /**
  22563. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22564. */
  22565. Camera.prototype.toString = function (fullDetails) {
  22566. var ret = "Name: " + this.name;
  22567. ret += ", type: " + this.getClassName();
  22568. if (this.animations) {
  22569. for (var i = 0; i < this.animations.length; i++) {
  22570. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22571. }
  22572. }
  22573. if (fullDetails) {
  22574. }
  22575. return ret;
  22576. };
  22577. Object.defineProperty(Camera.prototype, "globalPosition", {
  22578. get: function () {
  22579. return this._globalPosition;
  22580. },
  22581. enumerable: true,
  22582. configurable: true
  22583. });
  22584. Camera.prototype.getActiveMeshes = function () {
  22585. return this._activeMeshes;
  22586. };
  22587. Camera.prototype.isActiveMesh = function (mesh) {
  22588. return (this._activeMeshes.indexOf(mesh) !== -1);
  22589. };
  22590. /**
  22591. * Is this camera ready to be used/rendered
  22592. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22593. * @return true if the camera is ready
  22594. */
  22595. Camera.prototype.isReady = function (completeCheck) {
  22596. if (completeCheck === void 0) { completeCheck = false; }
  22597. if (completeCheck) {
  22598. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22599. var pp = _a[_i];
  22600. if (pp && !pp.isReady()) {
  22601. return false;
  22602. }
  22603. }
  22604. }
  22605. return _super.prototype.isReady.call(this, completeCheck);
  22606. };
  22607. //Cache
  22608. Camera.prototype._initCache = function () {
  22609. _super.prototype._initCache.call(this);
  22610. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22611. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22612. this._cache.mode = undefined;
  22613. this._cache.minZ = undefined;
  22614. this._cache.maxZ = undefined;
  22615. this._cache.fov = undefined;
  22616. this._cache.fovMode = undefined;
  22617. this._cache.aspectRatio = undefined;
  22618. this._cache.orthoLeft = undefined;
  22619. this._cache.orthoRight = undefined;
  22620. this._cache.orthoBottom = undefined;
  22621. this._cache.orthoTop = undefined;
  22622. this._cache.renderWidth = undefined;
  22623. this._cache.renderHeight = undefined;
  22624. };
  22625. Camera.prototype._updateCache = function (ignoreParentClass) {
  22626. if (!ignoreParentClass) {
  22627. _super.prototype._updateCache.call(this);
  22628. }
  22629. this._cache.position.copyFrom(this.position);
  22630. this._cache.upVector.copyFrom(this.upVector);
  22631. };
  22632. // Synchronized
  22633. Camera.prototype._isSynchronized = function () {
  22634. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22635. };
  22636. Camera.prototype._isSynchronizedViewMatrix = function () {
  22637. if (!_super.prototype._isSynchronized.call(this))
  22638. return false;
  22639. return this._cache.position.equals(this.position)
  22640. && this._cache.upVector.equals(this.upVector)
  22641. && this.isSynchronizedWithParent();
  22642. };
  22643. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22644. var check = this._cache.mode === this.mode
  22645. && this._cache.minZ === this.minZ
  22646. && this._cache.maxZ === this.maxZ;
  22647. if (!check) {
  22648. return false;
  22649. }
  22650. var engine = this.getEngine();
  22651. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22652. check = this._cache.fov === this.fov
  22653. && this._cache.fovMode === this.fovMode
  22654. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22655. }
  22656. else {
  22657. check = this._cache.orthoLeft === this.orthoLeft
  22658. && this._cache.orthoRight === this.orthoRight
  22659. && this._cache.orthoBottom === this.orthoBottom
  22660. && this._cache.orthoTop === this.orthoTop
  22661. && this._cache.renderWidth === engine.getRenderWidth()
  22662. && this._cache.renderHeight === engine.getRenderHeight();
  22663. }
  22664. return check;
  22665. };
  22666. // Controls
  22667. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22668. };
  22669. Camera.prototype.detachControl = function (element) {
  22670. };
  22671. Camera.prototype.update = function () {
  22672. this._checkInputs();
  22673. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22674. this._updateRigCameras();
  22675. }
  22676. };
  22677. Camera.prototype._checkInputs = function () {
  22678. this.onAfterCheckInputsObservable.notifyObservers(this);
  22679. };
  22680. Object.defineProperty(Camera.prototype, "rigCameras", {
  22681. get: function () {
  22682. return this._rigCameras;
  22683. },
  22684. enumerable: true,
  22685. configurable: true
  22686. });
  22687. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22688. get: function () {
  22689. return this._rigPostProcess;
  22690. },
  22691. enumerable: true,
  22692. configurable: true
  22693. });
  22694. /**
  22695. * Internal, gets the first post proces.
  22696. * @returns the first post process to be run on this camera.
  22697. */
  22698. Camera.prototype._getFirstPostProcess = function () {
  22699. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22700. if (this._postProcesses[ppIndex] !== null) {
  22701. return this._postProcesses[ppIndex];
  22702. }
  22703. }
  22704. return null;
  22705. };
  22706. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22707. // invalidate framebuffer
  22708. var firstPostProcess = this._getFirstPostProcess();
  22709. if (firstPostProcess) {
  22710. firstPostProcess.markTextureDirty();
  22711. }
  22712. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22713. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22714. var cam = this._rigCameras[i];
  22715. var rigPostProcess = cam._rigPostProcess;
  22716. // for VR rig, there does not have to be a post process
  22717. if (rigPostProcess) {
  22718. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22719. if (isPass) {
  22720. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22721. cam.isIntermediate = this._postProcesses.length === 0;
  22722. }
  22723. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22724. rigPostProcess.markTextureDirty();
  22725. }
  22726. else {
  22727. cam._postProcesses = this._postProcesses.slice(0);
  22728. }
  22729. }
  22730. };
  22731. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22732. if (insertAt === void 0) { insertAt = null; }
  22733. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22734. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22735. return 0;
  22736. }
  22737. if (insertAt == null || insertAt < 0) {
  22738. this._postProcesses.push(postProcess);
  22739. }
  22740. else if (this._postProcesses[insertAt] === null) {
  22741. this._postProcesses[insertAt] = postProcess;
  22742. }
  22743. else {
  22744. this._postProcesses.splice(insertAt, 0, postProcess);
  22745. }
  22746. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22747. return this._postProcesses.indexOf(postProcess);
  22748. };
  22749. Camera.prototype.detachPostProcess = function (postProcess) {
  22750. var idx = this._postProcesses.indexOf(postProcess);
  22751. if (idx !== -1) {
  22752. this._postProcesses[idx] = null;
  22753. }
  22754. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22755. };
  22756. Camera.prototype.getWorldMatrix = function () {
  22757. if (this._isSynchronizedViewMatrix()) {
  22758. return this._worldMatrix;
  22759. }
  22760. // Getting the the view matrix will also compute the world matrix.
  22761. this.getViewMatrix();
  22762. return this._worldMatrix;
  22763. };
  22764. Camera.prototype._getViewMatrix = function () {
  22765. return BABYLON.Matrix.Identity();
  22766. };
  22767. Camera.prototype.getViewMatrix = function (force) {
  22768. if (!force && this._isSynchronizedViewMatrix()) {
  22769. return this._computedViewMatrix;
  22770. }
  22771. this.updateCache();
  22772. this._computedViewMatrix = this._getViewMatrix();
  22773. this._currentRenderId = this.getScene().getRenderId();
  22774. this._childRenderId = this._currentRenderId;
  22775. this._refreshFrustumPlanes = true;
  22776. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22777. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22778. }
  22779. this.onViewMatrixChangedObservable.notifyObservers(this);
  22780. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22781. return this._computedViewMatrix;
  22782. };
  22783. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22784. this._doNotComputeProjectionMatrix = true;
  22785. if (projection !== undefined) {
  22786. this._projectionMatrix = projection;
  22787. }
  22788. };
  22789. ;
  22790. Camera.prototype.unfreezeProjectionMatrix = function () {
  22791. this._doNotComputeProjectionMatrix = false;
  22792. };
  22793. ;
  22794. Camera.prototype.getProjectionMatrix = function (force) {
  22795. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22796. return this._projectionMatrix;
  22797. }
  22798. // Cache
  22799. this._cache.mode = this.mode;
  22800. this._cache.minZ = this.minZ;
  22801. this._cache.maxZ = this.maxZ;
  22802. // Matrix
  22803. this._refreshFrustumPlanes = true;
  22804. var engine = this.getEngine();
  22805. var scene = this.getScene();
  22806. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22807. this._cache.fov = this.fov;
  22808. this._cache.fovMode = this.fovMode;
  22809. this._cache.aspectRatio = engine.getAspectRatio(this);
  22810. if (this.minZ <= 0) {
  22811. this.minZ = 0.1;
  22812. }
  22813. if (scene.useRightHandedSystem) {
  22814. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22815. }
  22816. else {
  22817. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22818. }
  22819. }
  22820. else {
  22821. var halfWidth = engine.getRenderWidth() / 2.0;
  22822. var halfHeight = engine.getRenderHeight() / 2.0;
  22823. if (scene.useRightHandedSystem) {
  22824. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22825. }
  22826. else {
  22827. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22828. }
  22829. this._cache.orthoLeft = this.orthoLeft;
  22830. this._cache.orthoRight = this.orthoRight;
  22831. this._cache.orthoBottom = this.orthoBottom;
  22832. this._cache.orthoTop = this.orthoTop;
  22833. this._cache.renderWidth = engine.getRenderWidth();
  22834. this._cache.renderHeight = engine.getRenderHeight();
  22835. }
  22836. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22837. return this._projectionMatrix;
  22838. };
  22839. Camera.prototype.getTranformationMatrix = function () {
  22840. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22841. return this._transformMatrix;
  22842. };
  22843. Camera.prototype.updateFrustumPlanes = function () {
  22844. if (!this._refreshFrustumPlanes) {
  22845. return;
  22846. }
  22847. this.getTranformationMatrix();
  22848. if (!this._frustumPlanes) {
  22849. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22850. }
  22851. else {
  22852. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22853. }
  22854. this._refreshFrustumPlanes = false;
  22855. };
  22856. Camera.prototype.isInFrustum = function (target) {
  22857. this.updateFrustumPlanes();
  22858. return target.isInFrustum(this._frustumPlanes);
  22859. };
  22860. Camera.prototype.isCompletelyInFrustum = function (target) {
  22861. this.updateFrustumPlanes();
  22862. return target.isCompletelyInFrustum(this._frustumPlanes);
  22863. };
  22864. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22865. if (length === void 0) { length = 100; }
  22866. if (!transform) {
  22867. transform = this.getWorldMatrix();
  22868. }
  22869. if (!origin) {
  22870. origin = this.position;
  22871. }
  22872. var forward = new BABYLON.Vector3(0, 0, 1);
  22873. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22874. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22875. return new BABYLON.Ray(origin, direction, length);
  22876. };
  22877. /**
  22878. * Releases resources associated with this node.
  22879. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22880. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22881. */
  22882. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22883. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22884. // Observables
  22885. this.onViewMatrixChangedObservable.clear();
  22886. this.onProjectionMatrixChangedObservable.clear();
  22887. this.onAfterCheckInputsObservable.clear();
  22888. this.onRestoreStateObservable.clear();
  22889. // Inputs
  22890. if (this.inputs) {
  22891. this.inputs.clear();
  22892. }
  22893. // Animations
  22894. this.getScene().stopAnimation(this);
  22895. // Remove from scene
  22896. this.getScene().removeCamera(this);
  22897. while (this._rigCameras.length > 0) {
  22898. var camera = this._rigCameras.pop();
  22899. if (camera) {
  22900. camera.dispose();
  22901. }
  22902. }
  22903. // Postprocesses
  22904. if (this._rigPostProcess) {
  22905. this._rigPostProcess.dispose(this);
  22906. this._rigPostProcess = null;
  22907. this._postProcesses = [];
  22908. }
  22909. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22910. this._rigPostProcess = null;
  22911. this._postProcesses = [];
  22912. }
  22913. else {
  22914. var i = this._postProcesses.length;
  22915. while (--i >= 0) {
  22916. var postProcess = this._postProcesses[i];
  22917. if (postProcess) {
  22918. postProcess.dispose(this);
  22919. }
  22920. }
  22921. }
  22922. // Render targets
  22923. var i = this.customRenderTargets.length;
  22924. while (--i >= 0) {
  22925. this.customRenderTargets[i].dispose();
  22926. }
  22927. this.customRenderTargets = [];
  22928. // Active Meshes
  22929. this._activeMeshes.dispose();
  22930. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22931. };
  22932. Object.defineProperty(Camera.prototype, "leftCamera", {
  22933. // ---- Camera rigs section ----
  22934. get: function () {
  22935. if (this._rigCameras.length < 1) {
  22936. return null;
  22937. }
  22938. return this._rigCameras[0];
  22939. },
  22940. enumerable: true,
  22941. configurable: true
  22942. });
  22943. Object.defineProperty(Camera.prototype, "rightCamera", {
  22944. get: function () {
  22945. if (this._rigCameras.length < 2) {
  22946. return null;
  22947. }
  22948. return this._rigCameras[1];
  22949. },
  22950. enumerable: true,
  22951. configurable: true
  22952. });
  22953. Camera.prototype.getLeftTarget = function () {
  22954. if (this._rigCameras.length < 1) {
  22955. return null;
  22956. }
  22957. return this._rigCameras[0].getTarget();
  22958. };
  22959. Camera.prototype.getRightTarget = function () {
  22960. if (this._rigCameras.length < 2) {
  22961. return null;
  22962. }
  22963. return this._rigCameras[1].getTarget();
  22964. };
  22965. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22966. if (this.cameraRigMode === mode) {
  22967. return;
  22968. }
  22969. while (this._rigCameras.length > 0) {
  22970. var camera = this._rigCameras.pop();
  22971. if (camera) {
  22972. camera.dispose();
  22973. }
  22974. }
  22975. this.cameraRigMode = mode;
  22976. this._cameraRigParams = {};
  22977. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22978. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22979. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22980. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22981. // create the rig cameras, unless none
  22982. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22983. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22984. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22985. if (leftCamera && rightCamera) {
  22986. this._rigCameras.push(leftCamera);
  22987. this._rigCameras.push(rightCamera);
  22988. }
  22989. }
  22990. switch (this.cameraRigMode) {
  22991. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22992. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22993. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22994. break;
  22995. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22996. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22997. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22998. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22999. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23000. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23001. break;
  23002. case Camera.RIG_MODE_VR:
  23003. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23004. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23005. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23006. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23007. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23008. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23009. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23010. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23011. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23012. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23013. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23014. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23015. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23016. if (metrics.compensateDistortion) {
  23017. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23018. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23019. }
  23020. break;
  23021. case Camera.RIG_MODE_WEBVR:
  23022. if (rigParams.vrDisplay) {
  23023. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23024. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23025. //Left eye
  23026. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23027. this._rigCameras[0].setCameraRigParameter("left", true);
  23028. //leaving this for future reference
  23029. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23030. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23031. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23032. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23033. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23034. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23035. this._rigCameras[0].parent = this;
  23036. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23037. //Right eye
  23038. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23039. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23040. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23041. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23042. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23043. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23044. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23045. this._rigCameras[1].parent = this;
  23046. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23047. if (Camera.UseAlternateWebVRRendering) {
  23048. this._rigCameras[1]._skipRendering = true;
  23049. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23050. }
  23051. }
  23052. break;
  23053. }
  23054. this._cascadePostProcessesToRigCams();
  23055. this.update();
  23056. };
  23057. Camera.prototype._getVRProjectionMatrix = function () {
  23058. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23059. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23060. return this._projectionMatrix;
  23061. };
  23062. Camera.prototype._updateCameraRotationMatrix = function () {
  23063. //Here for WebVR
  23064. };
  23065. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23066. //Here for WebVR
  23067. };
  23068. /**
  23069. * This function MUST be overwritten by the different WebVR cameras available.
  23070. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23071. */
  23072. Camera.prototype._getWebVRProjectionMatrix = function () {
  23073. return BABYLON.Matrix.Identity();
  23074. };
  23075. /**
  23076. * This function MUST be overwritten by the different WebVR cameras available.
  23077. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23078. */
  23079. Camera.prototype._getWebVRViewMatrix = function () {
  23080. return BABYLON.Matrix.Identity();
  23081. };
  23082. Camera.prototype.setCameraRigParameter = function (name, value) {
  23083. if (!this._cameraRigParams) {
  23084. this._cameraRigParams = {};
  23085. }
  23086. this._cameraRigParams[name] = value;
  23087. //provisionnally:
  23088. if (name === "interaxialDistance") {
  23089. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23090. }
  23091. };
  23092. /**
  23093. * needs to be overridden by children so sub has required properties to be copied
  23094. */
  23095. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23096. return null;
  23097. };
  23098. /**
  23099. * May need to be overridden by children
  23100. */
  23101. Camera.prototype._updateRigCameras = function () {
  23102. for (var i = 0; i < this._rigCameras.length; i++) {
  23103. this._rigCameras[i].minZ = this.minZ;
  23104. this._rigCameras[i].maxZ = this.maxZ;
  23105. this._rigCameras[i].fov = this.fov;
  23106. }
  23107. // only update viewport when ANAGLYPH
  23108. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23109. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23110. }
  23111. };
  23112. Camera.prototype._setupInputs = function () {
  23113. };
  23114. Camera.prototype.serialize = function () {
  23115. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23116. // Type
  23117. serializationObject.type = this.getClassName();
  23118. // Parent
  23119. if (this.parent) {
  23120. serializationObject.parentId = this.parent.id;
  23121. }
  23122. if (this.inputs) {
  23123. this.inputs.serialize(serializationObject);
  23124. }
  23125. // Animations
  23126. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23127. serializationObject.ranges = this.serializeAnimationRanges();
  23128. return serializationObject;
  23129. };
  23130. Camera.prototype.clone = function (name) {
  23131. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23132. };
  23133. Camera.prototype.getDirection = function (localAxis) {
  23134. var result = BABYLON.Vector3.Zero();
  23135. this.getDirectionToRef(localAxis, result);
  23136. return result;
  23137. };
  23138. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23139. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23140. };
  23141. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23142. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23143. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23144. switch (type) {
  23145. case "ArcRotateCamera":
  23146. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23147. case "DeviceOrientationCamera":
  23148. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23149. case "FollowCamera":
  23150. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23151. case "ArcFollowCamera":
  23152. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23153. case "GamepadCamera":
  23154. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23155. case "TouchCamera":
  23156. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23157. case "VirtualJoysticksCamera":
  23158. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23159. case "WebVRFreeCamera":
  23160. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23161. case "WebVRGamepadCamera":
  23162. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23163. case "VRDeviceOrientationFreeCamera":
  23164. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23165. case "VRDeviceOrientationGamepadCamera":
  23166. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23167. case "AnaglyphArcRotateCamera":
  23168. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23169. case "AnaglyphFreeCamera":
  23170. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23171. case "AnaglyphGamepadCamera":
  23172. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23173. case "AnaglyphUniversalCamera":
  23174. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23175. case "StereoscopicArcRotateCamera":
  23176. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23177. case "StereoscopicFreeCamera":
  23178. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23179. case "StereoscopicGamepadCamera":
  23180. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23181. case "StereoscopicUniversalCamera":
  23182. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23183. case "FreeCamera": // Forcing Universal here
  23184. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23185. default: // Universal Camera is the default value
  23186. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23187. }
  23188. };
  23189. Camera.prototype.computeWorldMatrix = function () {
  23190. return this.getWorldMatrix();
  23191. };
  23192. Camera.Parse = function (parsedCamera, scene) {
  23193. var type = parsedCamera.type;
  23194. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23195. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23196. // Parent
  23197. if (parsedCamera.parentId) {
  23198. camera._waitingParentId = parsedCamera.parentId;
  23199. }
  23200. //If camera has an input manager, let it parse inputs settings
  23201. if (camera.inputs) {
  23202. camera.inputs.parse(parsedCamera);
  23203. camera._setupInputs();
  23204. }
  23205. if (camera.setPosition) { // need to force position
  23206. camera.position.copyFromFloats(0, 0, 0);
  23207. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23208. }
  23209. // Target
  23210. if (parsedCamera.target) {
  23211. if (camera.setTarget) {
  23212. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23213. }
  23214. }
  23215. // Apply 3d rig, when found
  23216. if (parsedCamera.cameraRigMode) {
  23217. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23218. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23219. }
  23220. // Animations
  23221. if (parsedCamera.animations) {
  23222. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23223. var parsedAnimation = parsedCamera.animations[animationIndex];
  23224. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23225. }
  23226. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23227. }
  23228. if (parsedCamera.autoAnimate) {
  23229. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23230. }
  23231. return camera;
  23232. };
  23233. // Statics
  23234. Camera._PERSPECTIVE_CAMERA = 0;
  23235. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23236. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23237. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23238. Camera._RIG_MODE_NONE = 0;
  23239. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23240. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23241. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23242. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23243. Camera._RIG_MODE_VR = 20;
  23244. Camera._RIG_MODE_WEBVR = 21;
  23245. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23246. Camera.UseAlternateWebVRRendering = false;
  23247. __decorate([
  23248. BABYLON.serializeAsVector3()
  23249. ], Camera.prototype, "position", void 0);
  23250. __decorate([
  23251. BABYLON.serializeAsVector3()
  23252. ], Camera.prototype, "upVector", void 0);
  23253. __decorate([
  23254. BABYLON.serialize()
  23255. ], Camera.prototype, "orthoLeft", void 0);
  23256. __decorate([
  23257. BABYLON.serialize()
  23258. ], Camera.prototype, "orthoRight", void 0);
  23259. __decorate([
  23260. BABYLON.serialize()
  23261. ], Camera.prototype, "orthoBottom", void 0);
  23262. __decorate([
  23263. BABYLON.serialize()
  23264. ], Camera.prototype, "orthoTop", void 0);
  23265. __decorate([
  23266. BABYLON.serialize()
  23267. ], Camera.prototype, "fov", void 0);
  23268. __decorate([
  23269. BABYLON.serialize()
  23270. ], Camera.prototype, "minZ", void 0);
  23271. __decorate([
  23272. BABYLON.serialize()
  23273. ], Camera.prototype, "maxZ", void 0);
  23274. __decorate([
  23275. BABYLON.serialize()
  23276. ], Camera.prototype, "inertia", void 0);
  23277. __decorate([
  23278. BABYLON.serialize()
  23279. ], Camera.prototype, "mode", void 0);
  23280. __decorate([
  23281. BABYLON.serialize()
  23282. ], Camera.prototype, "layerMask", void 0);
  23283. __decorate([
  23284. BABYLON.serialize()
  23285. ], Camera.prototype, "fovMode", void 0);
  23286. __decorate([
  23287. BABYLON.serialize()
  23288. ], Camera.prototype, "cameraRigMode", void 0);
  23289. __decorate([
  23290. BABYLON.serialize()
  23291. ], Camera.prototype, "interaxialDistance", void 0);
  23292. __decorate([
  23293. BABYLON.serialize()
  23294. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23295. return Camera;
  23296. }(BABYLON.Node));
  23297. BABYLON.Camera = Camera;
  23298. })(BABYLON || (BABYLON = {}));
  23299. //# sourceMappingURL=babylon.camera.js.map
  23300. var BABYLON;
  23301. (function (BABYLON) {
  23302. var RenderingManager = /** @class */ (function () {
  23303. function RenderingManager(scene) {
  23304. this._renderingGroups = new Array();
  23305. this._autoClearDepthStencil = {};
  23306. this._customOpaqueSortCompareFn = {};
  23307. this._customAlphaTestSortCompareFn = {};
  23308. this._customTransparentSortCompareFn = {};
  23309. this._renderinGroupInfo = null;
  23310. this._scene = scene;
  23311. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23312. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23313. }
  23314. }
  23315. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23316. if (depth === void 0) { depth = true; }
  23317. if (stencil === void 0) { stencil = true; }
  23318. if (this._depthStencilBufferAlreadyCleaned) {
  23319. return;
  23320. }
  23321. this._scene.getEngine().clear(null, false, depth, stencil);
  23322. this._depthStencilBufferAlreadyCleaned = true;
  23323. };
  23324. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23325. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23326. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23327. var info = null;
  23328. if (observable) {
  23329. if (!this._renderinGroupInfo) {
  23330. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23331. }
  23332. info = this._renderinGroupInfo;
  23333. info.scene = this._scene;
  23334. info.camera = this._scene.activeCamera;
  23335. }
  23336. // Dispatch sprites
  23337. if (renderSprites) {
  23338. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23339. var manager = this._scene.spriteManagers[index];
  23340. this.dispatchSprites(manager);
  23341. }
  23342. }
  23343. // Render
  23344. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23345. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23346. var renderingGroup = this._renderingGroups[index];
  23347. if (!renderingGroup && !observable)
  23348. continue;
  23349. var renderingGroupMask = 0;
  23350. // Fire PRECLEAR stage
  23351. if (observable && info) {
  23352. renderingGroupMask = Math.pow(2, index);
  23353. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23354. info.renderingGroupId = index;
  23355. observable.notifyObservers(info, renderingGroupMask);
  23356. }
  23357. // Clear depth/stencil if needed
  23358. if (RenderingManager.AUTOCLEAR) {
  23359. var autoClear = this._autoClearDepthStencil[index];
  23360. if (autoClear && autoClear.autoClear) {
  23361. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23362. }
  23363. }
  23364. if (observable && info) {
  23365. // Fire PREOPAQUE stage
  23366. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23367. observable.notifyObservers(info, renderingGroupMask);
  23368. // Fire PRETRANSPARENT stage
  23369. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23370. observable.notifyObservers(info, renderingGroupMask);
  23371. }
  23372. if (renderingGroup)
  23373. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23374. // Fire POSTTRANSPARENT stage
  23375. if (observable && info) {
  23376. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23377. observable.notifyObservers(info, renderingGroupMask);
  23378. }
  23379. }
  23380. };
  23381. RenderingManager.prototype.reset = function () {
  23382. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23383. var renderingGroup = this._renderingGroups[index];
  23384. if (renderingGroup) {
  23385. renderingGroup.prepare();
  23386. }
  23387. }
  23388. };
  23389. RenderingManager.prototype.dispose = function () {
  23390. this.freeRenderingGroups();
  23391. this._renderingGroups.length = 0;
  23392. };
  23393. /**
  23394. * Clear the info related to rendering groups preventing retention points during dispose.
  23395. */
  23396. RenderingManager.prototype.freeRenderingGroups = function () {
  23397. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23398. var renderingGroup = this._renderingGroups[index];
  23399. if (renderingGroup) {
  23400. renderingGroup.dispose();
  23401. }
  23402. }
  23403. };
  23404. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23405. if (this._renderingGroups[renderingGroupId] === undefined) {
  23406. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23407. }
  23408. };
  23409. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23410. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23411. this._prepareRenderingGroup(renderingGroupId);
  23412. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23413. };
  23414. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23415. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23416. this._prepareRenderingGroup(renderingGroupId);
  23417. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23418. };
  23419. /**
  23420. * @param subMesh The submesh to dispatch
  23421. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23422. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23423. */
  23424. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23425. if (mesh === undefined) {
  23426. mesh = subMesh.getMesh();
  23427. }
  23428. var renderingGroupId = mesh.renderingGroupId || 0;
  23429. this._prepareRenderingGroup(renderingGroupId);
  23430. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23431. };
  23432. /**
  23433. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23434. * This allowed control for front to back rendering or reversly depending of the special needs.
  23435. *
  23436. * @param renderingGroupId The rendering group id corresponding to its index
  23437. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23438. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23439. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23440. */
  23441. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23442. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23443. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23444. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23445. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23446. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23447. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23448. if (this._renderingGroups[renderingGroupId]) {
  23449. var group = this._renderingGroups[renderingGroupId];
  23450. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23451. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23452. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23453. }
  23454. };
  23455. /**
  23456. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23457. *
  23458. * @param renderingGroupId The rendering group id corresponding to its index
  23459. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23460. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23461. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23462. */
  23463. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23464. if (depth === void 0) { depth = true; }
  23465. if (stencil === void 0) { stencil = true; }
  23466. this._autoClearDepthStencil[renderingGroupId] = {
  23467. autoClear: autoClearDepthStencil,
  23468. depth: depth,
  23469. stencil: stencil
  23470. };
  23471. };
  23472. /**
  23473. * The max id used for rendering groups (not included)
  23474. */
  23475. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23476. /**
  23477. * The min id used for rendering groups (included)
  23478. */
  23479. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23480. /**
  23481. * Used to globally prevent autoclearing scenes.
  23482. */
  23483. RenderingManager.AUTOCLEAR = true;
  23484. return RenderingManager;
  23485. }());
  23486. BABYLON.RenderingManager = RenderingManager;
  23487. })(BABYLON || (BABYLON = {}));
  23488. //# sourceMappingURL=babylon.renderingManager.js.map
  23489. var BABYLON;
  23490. (function (BABYLON) {
  23491. var RenderingGroup = /** @class */ (function () {
  23492. /**
  23493. * Creates a new rendering group.
  23494. * @param index The rendering group index
  23495. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23496. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23497. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23498. */
  23499. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23500. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23501. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23502. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23503. this.index = index;
  23504. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23505. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23506. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23507. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23508. this._particleSystems = new BABYLON.SmartArray(256);
  23509. this._spriteManagers = new BABYLON.SmartArray(256);
  23510. this._edgesRenderers = new BABYLON.SmartArray(16);
  23511. this._scene = scene;
  23512. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23513. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23514. this.transparentSortCompareFn = transparentSortCompareFn;
  23515. }
  23516. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23517. /**
  23518. * Set the opaque sort comparison function.
  23519. * If null the sub meshes will be render in the order they were created
  23520. */
  23521. set: function (value) {
  23522. this._opaqueSortCompareFn = value;
  23523. if (value) {
  23524. this._renderOpaque = this.renderOpaqueSorted;
  23525. }
  23526. else {
  23527. this._renderOpaque = RenderingGroup.renderUnsorted;
  23528. }
  23529. },
  23530. enumerable: true,
  23531. configurable: true
  23532. });
  23533. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23534. /**
  23535. * Set the alpha test sort comparison function.
  23536. * If null the sub meshes will be render in the order they were created
  23537. */
  23538. set: function (value) {
  23539. this._alphaTestSortCompareFn = value;
  23540. if (value) {
  23541. this._renderAlphaTest = this.renderAlphaTestSorted;
  23542. }
  23543. else {
  23544. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23545. }
  23546. },
  23547. enumerable: true,
  23548. configurable: true
  23549. });
  23550. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23551. /**
  23552. * Set the transparent sort comparison function.
  23553. * If null the sub meshes will be render in the order they were created
  23554. */
  23555. set: function (value) {
  23556. if (value) {
  23557. this._transparentSortCompareFn = value;
  23558. }
  23559. else {
  23560. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23561. }
  23562. this._renderTransparent = this.renderTransparentSorted;
  23563. },
  23564. enumerable: true,
  23565. configurable: true
  23566. });
  23567. /**
  23568. * Render all the sub meshes contained in the group.
  23569. * @param customRenderFunction Used to override the default render behaviour of the group.
  23570. * @returns true if rendered some submeshes.
  23571. */
  23572. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23573. if (customRenderFunction) {
  23574. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23575. return;
  23576. }
  23577. var engine = this._scene.getEngine();
  23578. // Depth only
  23579. if (this._depthOnlySubMeshes.length !== 0) {
  23580. engine.setColorWrite(false);
  23581. this._renderAlphaTest(this._depthOnlySubMeshes);
  23582. engine.setColorWrite(true);
  23583. }
  23584. // Opaque
  23585. if (this._opaqueSubMeshes.length !== 0) {
  23586. this._renderOpaque(this._opaqueSubMeshes);
  23587. }
  23588. // Alpha test
  23589. if (this._alphaTestSubMeshes.length !== 0) {
  23590. this._renderAlphaTest(this._alphaTestSubMeshes);
  23591. }
  23592. var stencilState = engine.getStencilBuffer();
  23593. engine.setStencilBuffer(false);
  23594. // Sprites
  23595. if (renderSprites) {
  23596. this._renderSprites();
  23597. }
  23598. // Particles
  23599. if (renderParticles) {
  23600. this._renderParticles(activeMeshes);
  23601. }
  23602. if (this.onBeforeTransparentRendering) {
  23603. this.onBeforeTransparentRendering();
  23604. }
  23605. // Transparent
  23606. if (this._transparentSubMeshes.length !== 0) {
  23607. this._renderTransparent(this._transparentSubMeshes);
  23608. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23609. }
  23610. // Set back stencil to false in case it changes before the edge renderer.
  23611. engine.setStencilBuffer(false);
  23612. // Edges
  23613. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23614. this._edgesRenderers.data[edgesRendererIndex].render();
  23615. }
  23616. // Restore Stencil state.
  23617. engine.setStencilBuffer(stencilState);
  23618. };
  23619. /**
  23620. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23621. * @param subMeshes The submeshes to render
  23622. */
  23623. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23624. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23625. };
  23626. /**
  23627. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23628. * @param subMeshes The submeshes to render
  23629. */
  23630. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23631. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23632. };
  23633. /**
  23634. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23635. * @param subMeshes The submeshes to render
  23636. */
  23637. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23638. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23639. };
  23640. /**
  23641. * Renders the submeshes in a specified order.
  23642. * @param subMeshes The submeshes to sort before render
  23643. * @param sortCompareFn The comparison function use to sort
  23644. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23645. * @param transparent Specifies to activate blending if true
  23646. */
  23647. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23648. var subIndex = 0;
  23649. var subMesh;
  23650. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23651. for (; subIndex < subMeshes.length; subIndex++) {
  23652. subMesh = subMeshes.data[subIndex];
  23653. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23654. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23655. }
  23656. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23657. if (sortCompareFn) {
  23658. sortedArray.sort(sortCompareFn);
  23659. }
  23660. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23661. subMesh = sortedArray[subIndex];
  23662. if (transparent) {
  23663. var material = subMesh.getMaterial();
  23664. if (material && material.needDepthPrePass) {
  23665. var engine = material.getScene().getEngine();
  23666. engine.setColorWrite(false);
  23667. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23668. subMesh.render(false);
  23669. engine.setColorWrite(true);
  23670. }
  23671. }
  23672. subMesh.render(transparent);
  23673. }
  23674. };
  23675. /**
  23676. * Renders the submeshes in the order they were dispatched (no sort applied).
  23677. * @param subMeshes The submeshes to render
  23678. */
  23679. RenderingGroup.renderUnsorted = function (subMeshes) {
  23680. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23681. var submesh = subMeshes.data[subIndex];
  23682. submesh.render(false);
  23683. }
  23684. };
  23685. /**
  23686. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23687. * are rendered back to front if in the same alpha index.
  23688. *
  23689. * @param a The first submesh
  23690. * @param b The second submesh
  23691. * @returns The result of the comparison
  23692. */
  23693. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23694. // Alpha index first
  23695. if (a._alphaIndex > b._alphaIndex) {
  23696. return 1;
  23697. }
  23698. if (a._alphaIndex < b._alphaIndex) {
  23699. return -1;
  23700. }
  23701. // Then distance to camera
  23702. return RenderingGroup.backToFrontSortCompare(a, b);
  23703. };
  23704. /**
  23705. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23706. * are rendered back to front.
  23707. *
  23708. * @param a The first submesh
  23709. * @param b The second submesh
  23710. * @returns The result of the comparison
  23711. */
  23712. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23713. // Then distance to camera
  23714. if (a._distanceToCamera < b._distanceToCamera) {
  23715. return 1;
  23716. }
  23717. if (a._distanceToCamera > b._distanceToCamera) {
  23718. return -1;
  23719. }
  23720. return 0;
  23721. };
  23722. /**
  23723. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23724. * are rendered front to back (prevent overdraw).
  23725. *
  23726. * @param a The first submesh
  23727. * @param b The second submesh
  23728. * @returns The result of the comparison
  23729. */
  23730. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23731. // Then distance to camera
  23732. if (a._distanceToCamera < b._distanceToCamera) {
  23733. return -1;
  23734. }
  23735. if (a._distanceToCamera > b._distanceToCamera) {
  23736. return 1;
  23737. }
  23738. return 0;
  23739. };
  23740. /**
  23741. * Resets the different lists of submeshes to prepare a new frame.
  23742. */
  23743. RenderingGroup.prototype.prepare = function () {
  23744. this._opaqueSubMeshes.reset();
  23745. this._transparentSubMeshes.reset();
  23746. this._alphaTestSubMeshes.reset();
  23747. this._depthOnlySubMeshes.reset();
  23748. this._particleSystems.reset();
  23749. this._spriteManagers.reset();
  23750. this._edgesRenderers.reset();
  23751. };
  23752. RenderingGroup.prototype.dispose = function () {
  23753. this._opaqueSubMeshes.dispose();
  23754. this._transparentSubMeshes.dispose();
  23755. this._alphaTestSubMeshes.dispose();
  23756. this._depthOnlySubMeshes.dispose();
  23757. this._particleSystems.dispose();
  23758. this._spriteManagers.dispose();
  23759. this._edgesRenderers.dispose();
  23760. };
  23761. /**
  23762. * Inserts the submesh in its correct queue depending on its material.
  23763. * @param subMesh The submesh to dispatch
  23764. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23765. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23766. */
  23767. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23768. // Get mesh and materials if not provided
  23769. if (mesh === undefined) {
  23770. mesh = subMesh.getMesh();
  23771. }
  23772. if (material === undefined) {
  23773. material = subMesh.getMaterial();
  23774. }
  23775. if (material === null || material === undefined) {
  23776. return;
  23777. }
  23778. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23779. this._transparentSubMeshes.push(subMesh);
  23780. }
  23781. else if (material.needAlphaTesting()) { // Alpha test
  23782. if (material.needDepthPrePass) {
  23783. this._depthOnlySubMeshes.push(subMesh);
  23784. }
  23785. this._alphaTestSubMeshes.push(subMesh);
  23786. }
  23787. else {
  23788. if (material.needDepthPrePass) {
  23789. this._depthOnlySubMeshes.push(subMesh);
  23790. }
  23791. this._opaqueSubMeshes.push(subMesh); // Opaque
  23792. }
  23793. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23794. this._edgesRenderers.push(mesh._edgesRenderer);
  23795. }
  23796. };
  23797. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23798. this._spriteManagers.push(spriteManager);
  23799. };
  23800. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23801. this._particleSystems.push(particleSystem);
  23802. };
  23803. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23804. if (this._particleSystems.length === 0) {
  23805. return;
  23806. }
  23807. // Particles
  23808. var activeCamera = this._scene.activeCamera;
  23809. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23810. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23811. var particleSystem = this._particleSystems.data[particleIndex];
  23812. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23813. continue;
  23814. }
  23815. var emitter = particleSystem.emitter;
  23816. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23817. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23818. }
  23819. }
  23820. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23821. };
  23822. RenderingGroup.prototype._renderSprites = function () {
  23823. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23824. return;
  23825. }
  23826. // Sprites
  23827. var activeCamera = this._scene.activeCamera;
  23828. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23829. for (var id = 0; id < this._spriteManagers.length; id++) {
  23830. var spriteManager = this._spriteManagers.data[id];
  23831. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23832. spriteManager.render();
  23833. }
  23834. }
  23835. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23836. };
  23837. return RenderingGroup;
  23838. }());
  23839. BABYLON.RenderingGroup = RenderingGroup;
  23840. })(BABYLON || (BABYLON = {}));
  23841. //# sourceMappingURL=babylon.renderingGroup.js.map
  23842. var BABYLON;
  23843. (function (BABYLON) {
  23844. /**
  23845. * Groups all the scene component constants in one place to ease maintenance.
  23846. * @hidden
  23847. */
  23848. var SceneComponentConstants = /** @class */ (function () {
  23849. function SceneComponentConstants() {
  23850. }
  23851. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23852. SceneComponentConstants.NAME_LAYER = "Layer";
  23853. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23854. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23855. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23856. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23857. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23858. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23859. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23860. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23861. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23862. return SceneComponentConstants;
  23863. }());
  23864. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23865. /**
  23866. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23867. * @hidden
  23868. */
  23869. var Stage = /** @class */ (function (_super) {
  23870. __extends(Stage, _super);
  23871. /**
  23872. * Hide ctor from the rest of the world.
  23873. * @param items The items to add.
  23874. */
  23875. function Stage(items) {
  23876. return _super.apply(this, items) || this;
  23877. }
  23878. /**
  23879. * Creates a new Stage.
  23880. * @returns A new instance of a Stage
  23881. */
  23882. Stage.Create = function () {
  23883. return Object.create(Stage.prototype);
  23884. };
  23885. /**
  23886. * Registers a step in an ordered way in the targeted stage.
  23887. * @param index Defines the position to register the step in
  23888. * @param component Defines the component attached to the step
  23889. * @param action Defines the action to launch during the step
  23890. */
  23891. Stage.prototype.registerStep = function (index, component, action) {
  23892. var i = 0;
  23893. var maxIndex = Number.MAX_VALUE;
  23894. for (; i < this.length && i < maxIndex; i++) {
  23895. var step = this[i];
  23896. maxIndex = step.index;
  23897. }
  23898. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23899. };
  23900. /**
  23901. * Clears all the steps from the stage.
  23902. */
  23903. Stage.prototype.clear = function () {
  23904. this.length = 0;
  23905. };
  23906. return Stage;
  23907. }(Array));
  23908. BABYLON.Stage = Stage;
  23909. })(BABYLON || (BABYLON = {}));
  23910. //# sourceMappingURL=babylon.sceneComponent.js.map
  23911. var BABYLON;
  23912. (function (BABYLON) {
  23913. /**
  23914. * Base class of the scene acting as a container for the different elements composing a scene.
  23915. * This class is dynamically extended by the different components of the scene increasing
  23916. * flexibility and reducing coupling.
  23917. */
  23918. var AbstractScene = /** @class */ (function () {
  23919. function AbstractScene() {
  23920. /** All of the cameras added to this scene
  23921. * @see http://doc.babylonjs.com/babylon101/cameras
  23922. */
  23923. this.cameras = new Array();
  23924. /**
  23925. * All of the lights added to this scene
  23926. * @see http://doc.babylonjs.com/babylon101/lights
  23927. */
  23928. this.lights = new Array();
  23929. /**
  23930. * All of the (abstract) meshes added to this scene
  23931. */
  23932. this.meshes = new Array();
  23933. /**
  23934. * The list of skeletons added to the scene
  23935. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23936. */
  23937. this.skeletons = new Array();
  23938. /**
  23939. * All of the particle systems added to this scene
  23940. * @see http://doc.babylonjs.com/babylon101/particles
  23941. */
  23942. this.particleSystems = new Array();
  23943. /**
  23944. * Gets a list of Animations associated with the scene
  23945. */
  23946. this.animations = [];
  23947. /**
  23948. * All of the animation groups added to this scene
  23949. * @see http://doc.babylonjs.com/how_to/group
  23950. */
  23951. this.animationGroups = new Array();
  23952. /**
  23953. * All of the multi-materials added to this scene
  23954. * @see http://doc.babylonjs.com/how_to/multi_materials
  23955. */
  23956. this.multiMaterials = new Array();
  23957. /**
  23958. * All of the materials added to this scene
  23959. * @see http://doc.babylonjs.com/babylon101/materials
  23960. */
  23961. this.materials = new Array();
  23962. /**
  23963. * The list of morph target managers added to the scene
  23964. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23965. */
  23966. this.morphTargetManagers = new Array();
  23967. /**
  23968. * The list of geometries used in the scene.
  23969. */
  23970. this.geometries = new Array();
  23971. /**
  23972. * All of the tranform nodes added to this scene
  23973. * @see http://doc.babylonjs.com/how_to/transformnode
  23974. */
  23975. this.transformNodes = new Array();
  23976. /**
  23977. * ActionManagers available on the scene.
  23978. */
  23979. this.actionManagers = new Array();
  23980. /**
  23981. * Sounds to keep.
  23982. */
  23983. this.sounds = new Array();
  23984. /**
  23985. * Textures to keep.
  23986. */
  23987. this.textures = new Array();
  23988. }
  23989. /**
  23990. * Adds a parser in the list of availables ones.
  23991. * @param name Defines the name of the parser
  23992. * @param parser Defines the parser to add
  23993. */
  23994. AbstractScene.AddParser = function (name, parser) {
  23995. this._BabylonFileParsers[name] = parser;
  23996. };
  23997. /**
  23998. * Parser json data and populate both a scene and its associated container object
  23999. * @param jsonData Defines the data to parse
  24000. * @param scene Defines the scene to parse the data for
  24001. * @param container Defines the container attached to the parsing sequence
  24002. * @param rootUrl Defines the root url of the data
  24003. */
  24004. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24005. for (var parserName in this._BabylonFileParsers) {
  24006. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24007. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24008. }
  24009. }
  24010. };
  24011. /**
  24012. * Stores the list of available parsers in the application.
  24013. */
  24014. AbstractScene._BabylonFileParsers = {};
  24015. return AbstractScene;
  24016. }());
  24017. BABYLON.AbstractScene = AbstractScene;
  24018. })(BABYLON || (BABYLON = {}));
  24019. //# sourceMappingURL=babylon.abstractScene.js.map
  24020. var BABYLON;
  24021. (function (BABYLON) {
  24022. /** @hidden */
  24023. var ClickInfo = /** @class */ (function () {
  24024. function ClickInfo() {
  24025. this._singleClick = false;
  24026. this._doubleClick = false;
  24027. this._hasSwiped = false;
  24028. this._ignore = false;
  24029. }
  24030. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24031. get: function () {
  24032. return this._singleClick;
  24033. },
  24034. set: function (b) {
  24035. this._singleClick = b;
  24036. },
  24037. enumerable: true,
  24038. configurable: true
  24039. });
  24040. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24041. get: function () {
  24042. return this._doubleClick;
  24043. },
  24044. set: function (b) {
  24045. this._doubleClick = b;
  24046. },
  24047. enumerable: true,
  24048. configurable: true
  24049. });
  24050. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24051. get: function () {
  24052. return this._hasSwiped;
  24053. },
  24054. set: function (b) {
  24055. this._hasSwiped = b;
  24056. },
  24057. enumerable: true,
  24058. configurable: true
  24059. });
  24060. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24061. get: function () {
  24062. return this._ignore;
  24063. },
  24064. set: function (b) {
  24065. this._ignore = b;
  24066. },
  24067. enumerable: true,
  24068. configurable: true
  24069. });
  24070. return ClickInfo;
  24071. }());
  24072. /**
  24073. * This class is used by the onRenderingGroupObservable
  24074. */
  24075. var RenderingGroupInfo = /** @class */ (function () {
  24076. function RenderingGroupInfo() {
  24077. }
  24078. /**
  24079. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  24080. * This stage will be fired no matter what
  24081. */
  24082. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  24083. /**
  24084. * Called before opaque object are rendered.
  24085. * This stage will be fired only if there's 3D Opaque content to render
  24086. */
  24087. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  24088. /**
  24089. * Called after the opaque objects are rendered and before the transparent ones
  24090. * This stage will be fired only if there's 3D transparent content to render
  24091. */
  24092. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  24093. /**
  24094. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  24095. * This stage will be fired no matter what
  24096. */
  24097. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  24098. return RenderingGroupInfo;
  24099. }());
  24100. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24101. /**
  24102. * Represents a scene to be rendered by the engine.
  24103. * @see http://doc.babylonjs.com/features/scene
  24104. */
  24105. var Scene = /** @class */ (function (_super) {
  24106. __extends(Scene, _super);
  24107. /**
  24108. * Creates a new Scene
  24109. * @param engine defines the engine to use to render this scene
  24110. */
  24111. function Scene(engine) {
  24112. var _this = _super.call(this) || this;
  24113. // Members
  24114. /**
  24115. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24116. */
  24117. _this.autoClear = true;
  24118. /**
  24119. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24120. */
  24121. _this.autoClearDepthAndStencil = true;
  24122. /**
  24123. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24124. */
  24125. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24126. /**
  24127. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24128. */
  24129. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24130. _this._forceWireframe = false;
  24131. _this._forcePointsCloud = false;
  24132. /**
  24133. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  24134. */
  24135. _this.forceShowBoundingBoxes = false;
  24136. /**
  24137. * Gets or sets a boolean indicating if animations are enabled
  24138. */
  24139. _this.animationsEnabled = true;
  24140. _this._animationPropertiesOverride = null;
  24141. /**
  24142. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24143. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24144. */
  24145. _this.useConstantAnimationDeltaTime = false;
  24146. /**
  24147. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24148. * Please note that it requires to run a ray cast through the scene on every frame
  24149. */
  24150. _this.constantlyUpdateMeshUnderPointer = false;
  24151. /**
  24152. * Defines the HTML cursor to use when hovering over interactive elements
  24153. */
  24154. _this.hoverCursor = "pointer";
  24155. /**
  24156. * Defines the HTML default cursor to use (empty by default)
  24157. */
  24158. _this.defaultCursor = "";
  24159. /**
  24160. * This is used to call preventDefault() on pointer down
  24161. * in order to block unwanted artifacts like system double clicks
  24162. */
  24163. _this.preventDefaultOnPointerDown = true;
  24164. // Metadata
  24165. /**
  24166. * Gets or sets user defined metadata
  24167. */
  24168. _this.metadata = null;
  24169. /**
  24170. * Use this array to add regular expressions used to disable offline support for specific urls
  24171. */
  24172. _this.disableOfflineSupportExceptionRules = new Array();
  24173. /**
  24174. * An event triggered when the scene is disposed.
  24175. */
  24176. _this.onDisposeObservable = new BABYLON.Observable();
  24177. _this._onDisposeObserver = null;
  24178. /**
  24179. * An event triggered before rendering the scene (right after animations and physics)
  24180. */
  24181. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24182. _this._onBeforeRenderObserver = null;
  24183. /**
  24184. * An event triggered after rendering the scene
  24185. */
  24186. _this.onAfterRenderObservable = new BABYLON.Observable();
  24187. _this._onAfterRenderObserver = null;
  24188. /**
  24189. * An event triggered before animating the scene
  24190. */
  24191. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24192. /**
  24193. * An event triggered after animations processing
  24194. */
  24195. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24196. /**
  24197. * An event triggered before draw calls are ready to be sent
  24198. */
  24199. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24200. /**
  24201. * An event triggered after draw calls have been sent
  24202. */
  24203. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24204. /**
  24205. * An event triggered when physic simulation is about to be run
  24206. */
  24207. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24208. /**
  24209. * An event triggered when physic simulation has been done
  24210. */
  24211. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24212. /**
  24213. * An event triggered when the scene is ready
  24214. */
  24215. _this.onReadyObservable = new BABYLON.Observable();
  24216. /**
  24217. * An event triggered before rendering a camera
  24218. */
  24219. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24220. _this._onBeforeCameraRenderObserver = null;
  24221. /**
  24222. * An event triggered after rendering a camera
  24223. */
  24224. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24225. _this._onAfterCameraRenderObserver = null;
  24226. /**
  24227. * An event triggered when active meshes evaluation is about to start
  24228. */
  24229. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24230. /**
  24231. * An event triggered when active meshes evaluation is done
  24232. */
  24233. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24234. /**
  24235. * An event triggered when particles rendering is about to start
  24236. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24237. */
  24238. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24239. /**
  24240. * An event triggered when particles rendering is done
  24241. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24242. */
  24243. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24244. /**
  24245. * An event triggered when sprites rendering is about to start
  24246. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24247. */
  24248. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24249. /**
  24250. * An event triggered when sprites rendering is done
  24251. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24252. */
  24253. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24254. /**
  24255. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24256. */
  24257. _this.onDataLoadedObservable = new BABYLON.Observable();
  24258. /**
  24259. * An event triggered when a camera is created
  24260. */
  24261. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24262. /**
  24263. * An event triggered when a camera is removed
  24264. */
  24265. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24266. /**
  24267. * An event triggered when a light is created
  24268. */
  24269. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24270. /**
  24271. * An event triggered when a light is removed
  24272. */
  24273. _this.onLightRemovedObservable = new BABYLON.Observable();
  24274. /**
  24275. * An event triggered when a geometry is created
  24276. */
  24277. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24278. /**
  24279. * An event triggered when a geometry is removed
  24280. */
  24281. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24282. /**
  24283. * An event triggered when a transform node is created
  24284. */
  24285. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24286. /**
  24287. * An event triggered when a transform node is removed
  24288. */
  24289. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24290. /**
  24291. * An event triggered when a mesh is created
  24292. */
  24293. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24294. /**
  24295. * An event triggered when a mesh is removed
  24296. */
  24297. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24298. /**
  24299. * An event triggered when render targets are about to be rendered
  24300. * Can happen multiple times per frame.
  24301. */
  24302. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24303. /**
  24304. * An event triggered when render targets were rendered.
  24305. * Can happen multiple times per frame.
  24306. */
  24307. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24308. /**
  24309. * An event triggered before calculating deterministic simulation step
  24310. */
  24311. _this.onBeforeStepObservable = new BABYLON.Observable();
  24312. /**
  24313. * An event triggered after calculating deterministic simulation step
  24314. */
  24315. _this.onAfterStepObservable = new BABYLON.Observable();
  24316. /**
  24317. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24318. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24319. * 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)
  24320. */
  24321. _this.onRenderingGroupObservable = new BABYLON.Observable();
  24322. // Animations
  24323. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24324. /**
  24325. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  24326. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24327. */
  24328. _this.onPrePointerObservable = new BABYLON.Observable();
  24329. /**
  24330. * Observable event triggered each time an input event is received from the rendering canvas
  24331. */
  24332. _this.onPointerObservable = new BABYLON.Observable();
  24333. _this._meshPickProceed = false;
  24334. _this._currentPickResult = null;
  24335. _this._previousPickResult = null;
  24336. _this._totalPointersPressed = 0;
  24337. _this._doubleClickOccured = false;
  24338. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24339. _this.cameraToUseForPointers = null;
  24340. _this._pointerX = 0;
  24341. _this._pointerY = 0;
  24342. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24343. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24344. _this._startingPointerTime = 0;
  24345. _this._previousStartingPointerTime = 0;
  24346. _this._pointerCaptures = {};
  24347. // Deterministic lockstep
  24348. _this._timeAccumulator = 0;
  24349. _this._currentStepId = 0;
  24350. _this._currentInternalStep = 0;
  24351. // Keyboard
  24352. /**
  24353. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24354. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24355. */
  24356. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24357. /**
  24358. * Observable event triggered each time an keyboard event is received from the hosting window
  24359. */
  24360. _this.onKeyboardObservable = new BABYLON.Observable();
  24361. // Coordinates system
  24362. _this._useRightHandedSystem = false;
  24363. // Fog
  24364. _this._fogEnabled = true;
  24365. _this._fogMode = Scene.FOGMODE_NONE;
  24366. /**
  24367. * Gets or sets the fog color to use
  24368. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24369. */
  24370. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24371. /**
  24372. * Gets or sets the fog density to use
  24373. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24374. */
  24375. _this.fogDensity = 0.1;
  24376. /**
  24377. * Gets or sets the fog start distance to use
  24378. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24379. */
  24380. _this.fogStart = 0;
  24381. /**
  24382. * Gets or sets the fog end distance to use
  24383. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24384. */
  24385. _this.fogEnd = 1000.0;
  24386. // Lights
  24387. _this._shadowsEnabled = true;
  24388. _this._lightsEnabled = true;
  24389. /** All of the active cameras added to this scene. */
  24390. _this.activeCameras = new Array();
  24391. // Textures
  24392. _this._texturesEnabled = true;
  24393. // Particles
  24394. /**
  24395. * Gets or sets a boolean indicating if particles are enabled on this scene
  24396. */
  24397. _this.particlesEnabled = true;
  24398. // Sprites
  24399. /**
  24400. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24401. */
  24402. _this.spritesEnabled = true;
  24403. /**
  24404. * All of the sprite managers added to this scene
  24405. * @see http://doc.babylonjs.com/babylon101/sprites
  24406. */
  24407. _this.spriteManagers = new Array();
  24408. // Skeletons
  24409. _this._skeletonsEnabled = true;
  24410. // Lens flares
  24411. /**
  24412. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24413. */
  24414. _this.lensFlaresEnabled = true;
  24415. // Collisions
  24416. /**
  24417. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24418. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24419. */
  24420. _this.collisionsEnabled = true;
  24421. /**
  24422. * Defines the gravity applied to this scene (used only for collisions)
  24423. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24424. */
  24425. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24426. // Postprocesses
  24427. /**
  24428. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24429. */
  24430. _this.postProcessesEnabled = true;
  24431. /**
  24432. * The list of postprocesses added to the scene
  24433. */
  24434. _this.postProcesses = new Array();
  24435. // Customs render targets
  24436. /**
  24437. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24438. */
  24439. _this.renderTargetsEnabled = true;
  24440. /**
  24441. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24442. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24443. */
  24444. _this.dumpNextRenderTargets = false;
  24445. /**
  24446. * The list of user defined render targets added to the scene
  24447. */
  24448. _this.customRenderTargets = new Array();
  24449. /**
  24450. * Gets the list of meshes imported to the scene through SceneLoader
  24451. */
  24452. _this.importedMeshesFiles = new Array();
  24453. // Probes
  24454. /**
  24455. * Gets or sets a boolean indicating if probes are enabled on this scene
  24456. */
  24457. _this.probesEnabled = true;
  24458. /**
  24459. * The list of reflection probes added to the scene
  24460. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24461. */
  24462. _this.reflectionProbes = new Array();
  24463. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24464. // Procedural textures
  24465. /**
  24466. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24467. */
  24468. _this.proceduralTexturesEnabled = true;
  24469. /**
  24470. * The list of procedural textures added to the scene
  24471. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24472. */
  24473. _this.proceduralTextures = new Array();
  24474. /**
  24475. * The list of sound tracks added to the scene
  24476. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24477. */
  24478. _this.soundTracks = new Array();
  24479. _this._audioEnabled = true;
  24480. _this._headphone = false;
  24481. // Performance counters
  24482. _this._totalVertices = new BABYLON.PerfCounter();
  24483. /** @hidden */
  24484. _this._activeIndices = new BABYLON.PerfCounter();
  24485. /** @hidden */
  24486. _this._activeParticles = new BABYLON.PerfCounter();
  24487. /** @hidden */
  24488. _this._activeBones = new BABYLON.PerfCounter();
  24489. _this._animationTime = 0;
  24490. /**
  24491. * Gets or sets a general scale for animation speed
  24492. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24493. */
  24494. _this.animationTimeScale = 1;
  24495. _this._renderId = 0;
  24496. _this._executeWhenReadyTimeoutId = -1;
  24497. _this._intermediateRendering = false;
  24498. _this._viewUpdateFlag = -1;
  24499. _this._projectionUpdateFlag = -1;
  24500. _this._alternateViewUpdateFlag = -1;
  24501. _this._alternateProjectionUpdateFlag = -1;
  24502. /** @hidden */
  24503. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24504. _this._activeRequests = new Array();
  24505. _this._pendingData = new Array();
  24506. _this._isDisposed = false;
  24507. /**
  24508. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24509. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24510. */
  24511. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24512. _this._activeMeshes = new BABYLON.SmartArray(256);
  24513. _this._processedMaterials = new BABYLON.SmartArray(256);
  24514. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24515. /** @hidden */
  24516. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24517. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24518. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24519. /** @hidden */
  24520. _this._activeAnimatables = new Array();
  24521. _this._transformMatrix = BABYLON.Matrix.Zero();
  24522. _this._useAlternateCameraConfiguration = false;
  24523. _this._alternateRendering = false;
  24524. /**
  24525. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24526. * This is useful if there are more lights that the maximum simulteanous authorized
  24527. */
  24528. _this.requireLightSorting = false;
  24529. _this._depthRenderer = {};
  24530. /**
  24531. * Backing store of defined scene components.
  24532. */
  24533. _this._components = [];
  24534. /**
  24535. * List of components to register on the next registration step.
  24536. */
  24537. _this._transientComponents = [];
  24538. /**
  24539. * Defines the actions happening during the per mesh ready checks.
  24540. */
  24541. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24542. /**
  24543. * Defines the actions happening during the per camera render target step.
  24544. */
  24545. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24546. /**
  24547. * Defines the actions happening just before the active camera is drawing.
  24548. */
  24549. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24550. /**
  24551. * Defines the actions happening just after the active camera is drawing.
  24552. */
  24553. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24554. _this._activeMeshesFrozen = false;
  24555. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24556. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24557. _this._engine.scenes.push(_this);
  24558. _this._uid = null;
  24559. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24560. if (BABYLON.PostProcessManager) {
  24561. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24562. }
  24563. if (BABYLON.OutlineRenderer) {
  24564. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24565. }
  24566. if (BABYLON.Tools.IsWindowObjectExist()) {
  24567. _this.attachControl();
  24568. }
  24569. //simplification queue
  24570. if (BABYLON.SimplificationQueue) {
  24571. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24572. }
  24573. //collision coordinator initialization. For now legacy per default.
  24574. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24575. // Uniform Buffer
  24576. _this._createUbo();
  24577. // Default Image processing definition
  24578. if (BABYLON.ImageProcessingConfiguration) {
  24579. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24580. }
  24581. return _this;
  24582. }
  24583. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24584. /** The fog is deactivated */
  24585. get: function () {
  24586. return Scene._FOGMODE_NONE;
  24587. },
  24588. enumerable: true,
  24589. configurable: true
  24590. });
  24591. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24592. /** The fog density is following an exponential function */
  24593. get: function () {
  24594. return Scene._FOGMODE_EXP;
  24595. },
  24596. enumerable: true,
  24597. configurable: true
  24598. });
  24599. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24600. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24601. get: function () {
  24602. return Scene._FOGMODE_EXP2;
  24603. },
  24604. enumerable: true,
  24605. configurable: true
  24606. });
  24607. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24608. /** The fog density is following a linear function. */
  24609. get: function () {
  24610. return Scene._FOGMODE_LINEAR;
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24616. /**
  24617. * Texture used in all pbr material as the reflection texture.
  24618. * As in the majority of the scene they are the same (exception for multi room and so on),
  24619. * this is easier to reference from here than from all the materials.
  24620. */
  24621. get: function () {
  24622. return this._environmentTexture;
  24623. },
  24624. /**
  24625. * Texture used in all pbr material as the reflection texture.
  24626. * As in the majority of the scene they are the same (exception for multi room and so on),
  24627. * this is easier to set here than in all the materials.
  24628. */
  24629. set: function (value) {
  24630. if (this._environmentTexture === value) {
  24631. return;
  24632. }
  24633. this._environmentTexture = value;
  24634. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24635. },
  24636. enumerable: true,
  24637. configurable: true
  24638. });
  24639. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24640. /**
  24641. * Default image processing configuration used either in the rendering
  24642. * Forward main pass or through the imageProcessingPostProcess if present.
  24643. * As in the majority of the scene they are the same (exception for multi camera),
  24644. * this is easier to reference from here than from all the materials and post process.
  24645. *
  24646. * No setter as we it is a shared configuration, you can set the values instead.
  24647. */
  24648. get: function () {
  24649. return this._imageProcessingConfiguration;
  24650. },
  24651. enumerable: true,
  24652. configurable: true
  24653. });
  24654. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24655. get: function () {
  24656. return this._forceWireframe;
  24657. },
  24658. /**
  24659. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24660. */
  24661. set: function (value) {
  24662. if (this._forceWireframe === value) {
  24663. return;
  24664. }
  24665. this._forceWireframe = value;
  24666. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24667. },
  24668. enumerable: true,
  24669. configurable: true
  24670. });
  24671. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24672. get: function () {
  24673. return this._forcePointsCloud;
  24674. },
  24675. /**
  24676. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24677. */
  24678. set: function (value) {
  24679. if (this._forcePointsCloud === value) {
  24680. return;
  24681. }
  24682. this._forcePointsCloud = value;
  24683. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24684. },
  24685. enumerable: true,
  24686. configurable: true
  24687. });
  24688. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24689. /**
  24690. * Gets or sets the animation properties override
  24691. */
  24692. get: function () {
  24693. return this._animationPropertiesOverride;
  24694. },
  24695. set: function (value) {
  24696. this._animationPropertiesOverride = value;
  24697. },
  24698. enumerable: true,
  24699. configurable: true
  24700. });
  24701. Object.defineProperty(Scene.prototype, "onDispose", {
  24702. /** Sets a function to be executed when this scene is disposed. */
  24703. set: function (callback) {
  24704. if (this._onDisposeObserver) {
  24705. this.onDisposeObservable.remove(this._onDisposeObserver);
  24706. }
  24707. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24708. },
  24709. enumerable: true,
  24710. configurable: true
  24711. });
  24712. Object.defineProperty(Scene.prototype, "beforeRender", {
  24713. /** Sets a function to be executed before rendering this scene */
  24714. set: function (callback) {
  24715. if (this._onBeforeRenderObserver) {
  24716. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24717. }
  24718. if (callback) {
  24719. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24720. }
  24721. },
  24722. enumerable: true,
  24723. configurable: true
  24724. });
  24725. Object.defineProperty(Scene.prototype, "afterRender", {
  24726. /** Sets a function to be executed after rendering this scene */
  24727. set: function (callback) {
  24728. if (this._onAfterRenderObserver) {
  24729. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24730. }
  24731. if (callback) {
  24732. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24733. }
  24734. },
  24735. enumerable: true,
  24736. configurable: true
  24737. });
  24738. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24739. /** Sets a function to be executed before rendering a camera*/
  24740. set: function (callback) {
  24741. if (this._onBeforeCameraRenderObserver) {
  24742. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24743. }
  24744. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24745. },
  24746. enumerable: true,
  24747. configurable: true
  24748. });
  24749. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24750. /** Sets a function to be executed after rendering a camera*/
  24751. set: function (callback) {
  24752. if (this._onAfterCameraRenderObserver) {
  24753. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24754. }
  24755. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24756. },
  24757. enumerable: true,
  24758. configurable: true
  24759. });
  24760. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24761. /**
  24762. * Gets the gamepad manager associated with the scene
  24763. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24764. */
  24765. get: function () {
  24766. if (!this._gamepadManager) {
  24767. this._gamepadManager = new BABYLON.GamepadManager(this);
  24768. }
  24769. return this._gamepadManager;
  24770. },
  24771. enumerable: true,
  24772. configurable: true
  24773. });
  24774. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24775. /**
  24776. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24777. */
  24778. get: function () {
  24779. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24785. get: function () {
  24786. return this._useRightHandedSystem;
  24787. },
  24788. /**
  24789. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24790. */
  24791. set: function (value) {
  24792. if (this._useRightHandedSystem === value) {
  24793. return;
  24794. }
  24795. this._useRightHandedSystem = value;
  24796. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24797. },
  24798. enumerable: true,
  24799. configurable: true
  24800. });
  24801. /**
  24802. * Sets the step Id used by deterministic lock step
  24803. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24804. * @param newStepId defines the step Id
  24805. */
  24806. Scene.prototype.setStepId = function (newStepId) {
  24807. this._currentStepId = newStepId;
  24808. };
  24809. ;
  24810. /**
  24811. * Gets the step Id used by deterministic lock step
  24812. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24813. * @returns the step Id
  24814. */
  24815. Scene.prototype.getStepId = function () {
  24816. return this._currentStepId;
  24817. };
  24818. ;
  24819. /**
  24820. * Gets the internal step used by deterministic lock step
  24821. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24822. * @returns the internal step
  24823. */
  24824. Scene.prototype.getInternalStep = function () {
  24825. return this._currentInternalStep;
  24826. };
  24827. ;
  24828. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24829. get: function () {
  24830. return this._fogEnabled;
  24831. },
  24832. /**
  24833. * Gets or sets a boolean indicating if fog is enabled on this scene
  24834. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24835. */
  24836. set: function (value) {
  24837. if (this._fogEnabled === value) {
  24838. return;
  24839. }
  24840. this._fogEnabled = value;
  24841. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24842. },
  24843. enumerable: true,
  24844. configurable: true
  24845. });
  24846. Object.defineProperty(Scene.prototype, "fogMode", {
  24847. get: function () {
  24848. return this._fogMode;
  24849. },
  24850. /**
  24851. * Gets or sets the fog mode to use
  24852. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24853. */
  24854. set: function (value) {
  24855. if (this._fogMode === value) {
  24856. return;
  24857. }
  24858. this._fogMode = value;
  24859. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24860. },
  24861. enumerable: true,
  24862. configurable: true
  24863. });
  24864. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24865. get: function () {
  24866. return this._shadowsEnabled;
  24867. },
  24868. /**
  24869. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24870. */
  24871. set: function (value) {
  24872. if (this._shadowsEnabled === value) {
  24873. return;
  24874. }
  24875. this._shadowsEnabled = value;
  24876. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24877. },
  24878. enumerable: true,
  24879. configurable: true
  24880. });
  24881. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24882. get: function () {
  24883. return this._lightsEnabled;
  24884. },
  24885. /**
  24886. * Gets or sets a boolean indicating if lights are enabled on this scene
  24887. */
  24888. set: function (value) {
  24889. if (this._lightsEnabled === value) {
  24890. return;
  24891. }
  24892. this._lightsEnabled = value;
  24893. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24894. },
  24895. enumerable: true,
  24896. configurable: true
  24897. });
  24898. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24899. /** The default material used on meshes when no material is affected */
  24900. get: function () {
  24901. if (!this._defaultMaterial) {
  24902. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24903. }
  24904. return this._defaultMaterial;
  24905. },
  24906. /** The default material used on meshes when no material is affected */
  24907. set: function (value) {
  24908. this._defaultMaterial = value;
  24909. },
  24910. enumerable: true,
  24911. configurable: true
  24912. });
  24913. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24914. get: function () {
  24915. return this._texturesEnabled;
  24916. },
  24917. /**
  24918. * Gets or sets a boolean indicating if textures are enabled on this scene
  24919. */
  24920. set: function (value) {
  24921. if (this._texturesEnabled === value) {
  24922. return;
  24923. }
  24924. this._texturesEnabled = value;
  24925. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24926. },
  24927. enumerable: true,
  24928. configurable: true
  24929. });
  24930. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24931. get: function () {
  24932. return this._skeletonsEnabled;
  24933. },
  24934. /**
  24935. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24936. */
  24937. set: function (value) {
  24938. if (this._skeletonsEnabled === value) {
  24939. return;
  24940. }
  24941. this._skeletonsEnabled = value;
  24942. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24943. },
  24944. enumerable: true,
  24945. configurable: true
  24946. });
  24947. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24948. /**
  24949. * Gets the postprocess render pipeline manager
  24950. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24951. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24952. */
  24953. get: function () {
  24954. if (!this._postProcessRenderPipelineManager) {
  24955. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24956. }
  24957. return this._postProcessRenderPipelineManager;
  24958. },
  24959. enumerable: true,
  24960. configurable: true
  24961. });
  24962. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24963. /**
  24964. * Gets the main soundtrack associated with the scene
  24965. */
  24966. get: function () {
  24967. if (!this._mainSoundTrack) {
  24968. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24969. }
  24970. return this._mainSoundTrack;
  24971. },
  24972. enumerable: true,
  24973. configurable: true
  24974. });
  24975. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24976. /** @hidden */
  24977. get: function () {
  24978. return this._alternateRendering;
  24979. },
  24980. enumerable: true,
  24981. configurable: true
  24982. });
  24983. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24984. /**
  24985. * Gets the list of frustum planes (built from the active camera)
  24986. */
  24987. get: function () {
  24988. return this._frustumPlanes;
  24989. },
  24990. enumerable: true,
  24991. configurable: true
  24992. });
  24993. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24994. /**
  24995. * Gets the current geometry buffer associated to the scene.
  24996. */
  24997. get: function () {
  24998. return this._geometryBufferRenderer;
  24999. },
  25000. /**
  25001. * Sets the current geometry buffer for the scene.
  25002. */
  25003. set: function (geometryBufferRenderer) {
  25004. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  25005. this._geometryBufferRenderer = geometryBufferRenderer;
  25006. }
  25007. },
  25008. enumerable: true,
  25009. configurable: true
  25010. });
  25011. /**
  25012. * Registers the transient components if needed.
  25013. */
  25014. Scene.prototype._registerTransientComponents = function () {
  25015. // Register components that have been associated lately to the scene.
  25016. if (this._transientComponents.length > 0) {
  25017. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25018. var component = _a[_i];
  25019. component.register();
  25020. }
  25021. this._transientComponents = [];
  25022. }
  25023. };
  25024. /**
  25025. * Add a component to the scene.
  25026. * Note that the ccomponent could be registered on th next frame if this is called after
  25027. * the register component stage.
  25028. * @param component Defines the component to add to the scene
  25029. */
  25030. Scene.prototype._addComponent = function (component) {
  25031. this._components.push(component);
  25032. this._transientComponents.push(component);
  25033. };
  25034. /**
  25035. * Gets a component from the scene.
  25036. * @param name defines the name of the component to retrieve
  25037. * @returns the component or null if not present
  25038. */
  25039. Scene.prototype._getComponent = function (name) {
  25040. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25041. var component = _a[_i];
  25042. if (component.name === name) {
  25043. return component;
  25044. }
  25045. }
  25046. return null;
  25047. };
  25048. Object.defineProperty(Scene.prototype, "debugLayer", {
  25049. /**
  25050. * Gets the debug layer (aka Inspector) associated with the scene
  25051. * @see http://doc.babylonjs.com/features/playground_debuglayer
  25052. */
  25053. get: function () {
  25054. if (!this._debugLayer) {
  25055. this._debugLayer = new BABYLON.DebugLayer(this);
  25056. }
  25057. return this._debugLayer;
  25058. },
  25059. enumerable: true,
  25060. configurable: true
  25061. });
  25062. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25063. /**
  25064. * Gets a boolean indicating if collisions are processed on a web worker
  25065. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25066. */
  25067. get: function () {
  25068. return this._workerCollisions;
  25069. },
  25070. set: function (enabled) {
  25071. if (!BABYLON.CollisionCoordinatorLegacy) {
  25072. return;
  25073. }
  25074. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25075. this._workerCollisions = enabled;
  25076. if (this.collisionCoordinator) {
  25077. this.collisionCoordinator.destroy();
  25078. }
  25079. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25080. this.collisionCoordinator.init(this);
  25081. },
  25082. enumerable: true,
  25083. configurable: true
  25084. });
  25085. Object.defineProperty(Scene.prototype, "selectionOctree", {
  25086. /**
  25087. * Gets the octree used to boost mesh selection (picking)
  25088. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  25089. */
  25090. get: function () {
  25091. return this._selectionOctree;
  25092. },
  25093. enumerable: true,
  25094. configurable: true
  25095. });
  25096. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25097. /**
  25098. * Gets the mesh that is currently under the pointer
  25099. */
  25100. get: function () {
  25101. return this._pointerOverMesh;
  25102. },
  25103. enumerable: true,
  25104. configurable: true
  25105. });
  25106. Object.defineProperty(Scene.prototype, "pointerX", {
  25107. /**
  25108. * Gets the current on-screen X position of the pointer
  25109. */
  25110. get: function () {
  25111. return this._pointerX;
  25112. },
  25113. enumerable: true,
  25114. configurable: true
  25115. });
  25116. Object.defineProperty(Scene.prototype, "pointerY", {
  25117. /**
  25118. * Gets the current on-screen Y position of the pointer
  25119. */
  25120. get: function () {
  25121. return this._pointerY;
  25122. },
  25123. enumerable: true,
  25124. configurable: true
  25125. });
  25126. /**
  25127. * Gets the cached material (ie. the latest rendered one)
  25128. * @returns the cached material
  25129. */
  25130. Scene.prototype.getCachedMaterial = function () {
  25131. return this._cachedMaterial;
  25132. };
  25133. /**
  25134. * Gets the cached effect (ie. the latest rendered one)
  25135. * @returns the cached effect
  25136. */
  25137. Scene.prototype.getCachedEffect = function () {
  25138. return this._cachedEffect;
  25139. };
  25140. /**
  25141. * Gets the cached visibility state (ie. the latest rendered one)
  25142. * @returns the cached visibility state
  25143. */
  25144. Scene.prototype.getCachedVisibility = function () {
  25145. return this._cachedVisibility;
  25146. };
  25147. /**
  25148. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25149. * @param material defines the current material
  25150. * @param effect defines the current effect
  25151. * @param visibility defines the current visibility state
  25152. * @returns true if one parameter is not cached
  25153. */
  25154. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25155. if (visibility === void 0) { visibility = 1; }
  25156. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25157. };
  25158. /**
  25159. * Gets the bounding box renderer associated with the scene
  25160. * @returns a BoundingBoxRenderer
  25161. */
  25162. Scene.prototype.getBoundingBoxRenderer = function () {
  25163. if (!this._boundingBoxRenderer) {
  25164. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  25165. }
  25166. return this._boundingBoxRenderer;
  25167. };
  25168. /**
  25169. * Gets the outline renderer associated with the scene
  25170. * @returns a OutlineRenderer
  25171. */
  25172. Scene.prototype.getOutlineRenderer = function () {
  25173. return this._outlineRenderer;
  25174. };
  25175. /**
  25176. * Gets the engine associated with the scene
  25177. * @returns an Engine
  25178. */
  25179. Scene.prototype.getEngine = function () {
  25180. return this._engine;
  25181. };
  25182. /**
  25183. * Gets the total number of vertices rendered per frame
  25184. * @returns the total number of vertices rendered per frame
  25185. */
  25186. Scene.prototype.getTotalVertices = function () {
  25187. return this._totalVertices.current;
  25188. };
  25189. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25190. /**
  25191. * Gets the performance counter for total vertices
  25192. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25193. */
  25194. get: function () {
  25195. return this._totalVertices;
  25196. },
  25197. enumerable: true,
  25198. configurable: true
  25199. });
  25200. /**
  25201. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25202. * @returns the total number of active indices rendered per frame
  25203. */
  25204. Scene.prototype.getActiveIndices = function () {
  25205. return this._activeIndices.current;
  25206. };
  25207. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25208. /**
  25209. * Gets the performance counter for active indices
  25210. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25211. */
  25212. get: function () {
  25213. return this._activeIndices;
  25214. },
  25215. enumerable: true,
  25216. configurable: true
  25217. });
  25218. /**
  25219. * Gets the total number of active particles rendered per frame
  25220. * @returns the total number of active particles rendered per frame
  25221. */
  25222. Scene.prototype.getActiveParticles = function () {
  25223. return this._activeParticles.current;
  25224. };
  25225. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25226. /**
  25227. * Gets the performance counter for active particles
  25228. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25229. */
  25230. get: function () {
  25231. return this._activeParticles;
  25232. },
  25233. enumerable: true,
  25234. configurable: true
  25235. });
  25236. /**
  25237. * Gets the total number of active bones rendered per frame
  25238. * @returns the total number of active bones rendered per frame
  25239. */
  25240. Scene.prototype.getActiveBones = function () {
  25241. return this._activeBones.current;
  25242. };
  25243. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25244. /**
  25245. * Gets the performance counter for active bones
  25246. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25247. */
  25248. get: function () {
  25249. return this._activeBones;
  25250. },
  25251. enumerable: true,
  25252. configurable: true
  25253. });
  25254. /** @hidden */
  25255. Scene.prototype.getInterFramePerfCounter = function () {
  25256. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25257. return 0;
  25258. };
  25259. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25260. /** @hidden */
  25261. get: function () {
  25262. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25263. return null;
  25264. },
  25265. enumerable: true,
  25266. configurable: true
  25267. });
  25268. /** @hidden */
  25269. Scene.prototype.getLastFrameDuration = function () {
  25270. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25271. return 0;
  25272. };
  25273. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25274. /** @hidden */
  25275. get: function () {
  25276. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25277. return null;
  25278. },
  25279. enumerable: true,
  25280. configurable: true
  25281. });
  25282. /** @hidden */
  25283. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25284. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25285. return 0;
  25286. };
  25287. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25288. /** @hidden */
  25289. get: function () {
  25290. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25291. return null;
  25292. },
  25293. enumerable: true,
  25294. configurable: true
  25295. });
  25296. /**
  25297. * Gets the array of active meshes
  25298. * @returns an array of AbstractMesh
  25299. */
  25300. Scene.prototype.getActiveMeshes = function () {
  25301. return this._activeMeshes;
  25302. };
  25303. /** @hidden */
  25304. Scene.prototype.getRenderTargetsDuration = function () {
  25305. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25306. return 0;
  25307. };
  25308. /** @hidden */
  25309. Scene.prototype.getRenderDuration = function () {
  25310. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25311. return 0;
  25312. };
  25313. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25314. /** @hidden */
  25315. get: function () {
  25316. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25317. return null;
  25318. },
  25319. enumerable: true,
  25320. configurable: true
  25321. });
  25322. /** @hidden */
  25323. Scene.prototype.getParticlesDuration = function () {
  25324. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25325. return 0;
  25326. };
  25327. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25328. /** @hidden */
  25329. get: function () {
  25330. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25331. return null;
  25332. },
  25333. enumerable: true,
  25334. configurable: true
  25335. });
  25336. /** @hidden */
  25337. Scene.prototype.getSpritesDuration = function () {
  25338. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25339. return 0;
  25340. };
  25341. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25342. /** @hidden */
  25343. get: function () {
  25344. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25345. return null;
  25346. },
  25347. enumerable: true,
  25348. configurable: true
  25349. });
  25350. /**
  25351. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25352. * @returns a number
  25353. */
  25354. Scene.prototype.getAnimationRatio = function () {
  25355. return this._animationRatio;
  25356. };
  25357. /**
  25358. * Gets an unique Id for the current frame
  25359. * @returns a number
  25360. */
  25361. Scene.prototype.getRenderId = function () {
  25362. return this._renderId;
  25363. };
  25364. /** Call this function if you want to manually increment the render Id*/
  25365. Scene.prototype.incrementRenderId = function () {
  25366. this._renderId++;
  25367. };
  25368. Scene.prototype._updatePointerPosition = function (evt) {
  25369. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25370. if (!canvasRect) {
  25371. return;
  25372. }
  25373. this._pointerX = evt.clientX - canvasRect.left;
  25374. this._pointerY = evt.clientY - canvasRect.top;
  25375. this._unTranslatedPointerX = this._pointerX;
  25376. this._unTranslatedPointerY = this._pointerY;
  25377. };
  25378. Scene.prototype._createUbo = function () {
  25379. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25380. this._sceneUbo.addUniform("viewProjection", 16);
  25381. this._sceneUbo.addUniform("view", 16);
  25382. };
  25383. Scene.prototype._createAlternateUbo = function () {
  25384. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25385. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25386. this._alternateSceneUbo.addUniform("view", 16);
  25387. };
  25388. // Pointers handling
  25389. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25390. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25391. if (result) {
  25392. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25393. }
  25394. return result;
  25395. };
  25396. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25397. if (pointerInfo.pickInfo) {
  25398. if (!pointerInfo.pickInfo.ray) {
  25399. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25400. }
  25401. }
  25402. };
  25403. /**
  25404. * Use this method to simulate a pointer move on a mesh
  25405. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25406. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25407. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25408. * @returns the current scene
  25409. */
  25410. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25411. var evt = new PointerEvent("pointermove", pointerEventInit);
  25412. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25413. return this;
  25414. }
  25415. return this._processPointerMove(pickResult, evt);
  25416. };
  25417. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25418. var canvas = this._engine.getRenderingCanvas();
  25419. if (!canvas) {
  25420. return this;
  25421. }
  25422. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25423. this.setPointerOverSprite(null);
  25424. this.setPointerOverMesh(pickResult.pickedMesh);
  25425. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25426. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25427. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25428. }
  25429. else {
  25430. canvas.style.cursor = this.hoverCursor;
  25431. }
  25432. }
  25433. else {
  25434. canvas.style.cursor = this.defaultCursor;
  25435. }
  25436. }
  25437. else {
  25438. this.setPointerOverMesh(null);
  25439. // Sprites
  25440. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25441. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25442. this.setPointerOverSprite(pickResult.pickedSprite);
  25443. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25444. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25445. }
  25446. else {
  25447. canvas.style.cursor = this.hoverCursor;
  25448. }
  25449. }
  25450. else {
  25451. this.setPointerOverSprite(null);
  25452. // Restore pointer
  25453. canvas.style.cursor = this.defaultCursor;
  25454. }
  25455. }
  25456. if (pickResult) {
  25457. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25458. if (this.onPointerMove) {
  25459. this.onPointerMove(evt, pickResult, type);
  25460. }
  25461. if (this.onPointerObservable.hasObservers()) {
  25462. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25463. this._setRayOnPointerInfo(pi);
  25464. this.onPointerObservable.notifyObservers(pi, type);
  25465. }
  25466. }
  25467. return this;
  25468. };
  25469. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25470. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25471. if (pickResult) {
  25472. pi.ray = pickResult.ray;
  25473. }
  25474. this.onPrePointerObservable.notifyObservers(pi, type);
  25475. if (pi.skipOnPointerObservable) {
  25476. return true;
  25477. }
  25478. else {
  25479. return false;
  25480. }
  25481. };
  25482. /**
  25483. * Use this method to simulate a pointer down on a mesh
  25484. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25485. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25486. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25487. * @returns the current scene
  25488. */
  25489. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25490. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25491. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25492. return this;
  25493. }
  25494. return this._processPointerDown(pickResult, evt);
  25495. };
  25496. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25497. var _this = this;
  25498. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25499. this._pickedDownMesh = pickResult.pickedMesh;
  25500. var actionManager = pickResult.pickedMesh.actionManager;
  25501. if (actionManager) {
  25502. if (actionManager.hasPickTriggers) {
  25503. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25504. switch (evt.button) {
  25505. case 0:
  25506. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25507. break;
  25508. case 1:
  25509. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25510. break;
  25511. case 2:
  25512. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25513. break;
  25514. }
  25515. }
  25516. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25517. window.setTimeout(function () {
  25518. 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);
  25519. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25520. if (_this._totalPointersPressed !== 0 &&
  25521. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25522. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25523. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25524. _this._startingPointerTime = 0;
  25525. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25526. }
  25527. }
  25528. }, Scene.LongPressDelay);
  25529. }
  25530. }
  25531. }
  25532. if (pickResult) {
  25533. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25534. if (this.onPointerDown) {
  25535. this.onPointerDown(evt, pickResult, type);
  25536. }
  25537. if (this.onPointerObservable.hasObservers()) {
  25538. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25539. this._setRayOnPointerInfo(pi);
  25540. this.onPointerObservable.notifyObservers(pi, type);
  25541. }
  25542. }
  25543. return this;
  25544. };
  25545. /**
  25546. * Use this method to simulate a pointer up on a mesh
  25547. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25548. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25549. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25550. * @returns the current scene
  25551. */
  25552. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25553. var evt = new PointerEvent("pointerup", pointerEventInit);
  25554. var clickInfo = new ClickInfo();
  25555. clickInfo.singleClick = true;
  25556. clickInfo.ignore = true;
  25557. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25558. return this;
  25559. }
  25560. return this._processPointerUp(pickResult, evt, clickInfo);
  25561. };
  25562. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25563. if (pickResult && pickResult && pickResult.pickedMesh) {
  25564. this._pickedUpMesh = pickResult.pickedMesh;
  25565. if (this._pickedDownMesh === this._pickedUpMesh) {
  25566. if (this.onPointerPick) {
  25567. this.onPointerPick(evt, pickResult);
  25568. }
  25569. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25570. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25571. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25572. this._setRayOnPointerInfo(pi);
  25573. this.onPointerObservable.notifyObservers(pi, type_1);
  25574. }
  25575. }
  25576. if (pickResult.pickedMesh.actionManager) {
  25577. if (clickInfo.ignore) {
  25578. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25579. }
  25580. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25581. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25582. }
  25583. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25584. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25585. }
  25586. }
  25587. }
  25588. if (this._pickedDownMesh &&
  25589. this._pickedDownMesh.actionManager &&
  25590. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25591. this._pickedDownMesh !== this._pickedUpMesh) {
  25592. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25593. }
  25594. var type = BABYLON.PointerEventTypes.POINTERUP;
  25595. if (this.onPointerObservable.hasObservers()) {
  25596. if (!clickInfo.ignore) {
  25597. if (!clickInfo.hasSwiped) {
  25598. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25599. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25600. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25601. this._setRayOnPointerInfo(pi);
  25602. this.onPointerObservable.notifyObservers(pi, type_2);
  25603. }
  25604. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25605. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25606. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25607. this._setRayOnPointerInfo(pi);
  25608. this.onPointerObservable.notifyObservers(pi, type_3);
  25609. }
  25610. }
  25611. }
  25612. else {
  25613. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25614. this._setRayOnPointerInfo(pi);
  25615. this.onPointerObservable.notifyObservers(pi, type);
  25616. }
  25617. }
  25618. if (this.onPointerUp) {
  25619. this.onPointerUp(evt, pickResult, type);
  25620. }
  25621. return this;
  25622. };
  25623. /**
  25624. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25625. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25626. * @returns true if the pointer was captured
  25627. */
  25628. Scene.prototype.isPointerCaptured = function (pointerId) {
  25629. if (pointerId === void 0) { pointerId = 0; }
  25630. return this._pointerCaptures[pointerId];
  25631. };
  25632. /**
  25633. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25634. * @param attachUp defines if you want to attach events to pointerup
  25635. * @param attachDown defines if you want to attach events to pointerdown
  25636. * @param attachMove defines if you want to attach events to pointermove
  25637. */
  25638. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25639. var _this = this;
  25640. if (attachUp === void 0) { attachUp = true; }
  25641. if (attachDown === void 0) { attachDown = true; }
  25642. if (attachMove === void 0) { attachMove = true; }
  25643. this._initActionManager = function (act, clickInfo) {
  25644. if (!_this._meshPickProceed) {
  25645. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25646. _this._currentPickResult = pickResult;
  25647. if (pickResult) {
  25648. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25649. }
  25650. _this._meshPickProceed = true;
  25651. }
  25652. return act;
  25653. };
  25654. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25655. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25656. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25657. btn !== _this._previousButtonPressed) {
  25658. _this._doubleClickOccured = false;
  25659. clickInfo.singleClick = true;
  25660. clickInfo.ignore = false;
  25661. cb(clickInfo, _this._currentPickResult);
  25662. }
  25663. };
  25664. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25665. var clickInfo = new ClickInfo();
  25666. _this._currentPickResult = null;
  25667. var act = null;
  25668. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25669. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25670. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25671. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25672. act = _this._initActionManager(act, clickInfo);
  25673. if (act)
  25674. checkPicking = act.hasPickTriggers;
  25675. }
  25676. if (checkPicking) {
  25677. var btn = evt.button;
  25678. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25679. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25680. if (!clickInfo.hasSwiped) {
  25681. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25682. if (!checkSingleClickImmediately) {
  25683. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25684. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25685. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25686. act = _this._initActionManager(act, clickInfo);
  25687. if (act)
  25688. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25689. }
  25690. }
  25691. if (checkSingleClickImmediately) {
  25692. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25693. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25694. btn !== _this._previousButtonPressed) {
  25695. clickInfo.singleClick = true;
  25696. cb(clickInfo, _this._currentPickResult);
  25697. }
  25698. }
  25699. // at least one double click is required to be check and exclusive double click is enabled
  25700. else {
  25701. // wait that no double click has been raised during the double click delay
  25702. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25703. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25704. }
  25705. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25706. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25707. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25708. act = _this._initActionManager(act, clickInfo);
  25709. if (act)
  25710. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25711. }
  25712. if (checkDoubleClick) {
  25713. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25714. if (btn === _this._previousButtonPressed &&
  25715. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25716. !_this._doubleClickOccured) {
  25717. // pointer has not moved for 2 clicks, it's a double click
  25718. if (!clickInfo.hasSwiped &&
  25719. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25720. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25721. _this._previousStartingPointerTime = 0;
  25722. _this._doubleClickOccured = true;
  25723. clickInfo.doubleClick = true;
  25724. clickInfo.ignore = false;
  25725. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25726. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25727. }
  25728. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25729. cb(clickInfo, _this._currentPickResult);
  25730. }
  25731. // if the two successive clicks are too far, it's just two simple clicks
  25732. else {
  25733. _this._doubleClickOccured = false;
  25734. _this._previousStartingPointerTime = _this._startingPointerTime;
  25735. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25736. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25737. _this._previousButtonPressed = btn;
  25738. if (Scene.ExclusiveDoubleClickMode) {
  25739. if (_this._previousDelayedSimpleClickTimeout) {
  25740. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25741. }
  25742. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25743. cb(clickInfo, _this._previousPickResult);
  25744. }
  25745. else {
  25746. cb(clickInfo, _this._currentPickResult);
  25747. }
  25748. }
  25749. }
  25750. // just the first click of the double has been raised
  25751. else {
  25752. _this._doubleClickOccured = false;
  25753. _this._previousStartingPointerTime = _this._startingPointerTime;
  25754. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25755. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25756. _this._previousButtonPressed = btn;
  25757. }
  25758. }
  25759. }
  25760. }
  25761. clickInfo.ignore = true;
  25762. cb(clickInfo, _this._currentPickResult);
  25763. };
  25764. this._spritePredicate = function (sprite) {
  25765. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25766. };
  25767. this._onPointerMove = function (evt) {
  25768. _this._updatePointerPosition(evt);
  25769. // PreObservable support
  25770. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25771. return;
  25772. }
  25773. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25774. return;
  25775. }
  25776. if (!_this.pointerMovePredicate) {
  25777. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25778. }
  25779. // Meshes
  25780. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25781. _this._processPointerMove(pickResult, evt);
  25782. };
  25783. this._onPointerDown = function (evt) {
  25784. _this._totalPointersPressed++;
  25785. _this._pickedDownMesh = null;
  25786. _this._meshPickProceed = false;
  25787. _this._updatePointerPosition(evt);
  25788. if (_this.preventDefaultOnPointerDown && canvas) {
  25789. evt.preventDefault();
  25790. canvas.focus();
  25791. }
  25792. // PreObservable support
  25793. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25794. return;
  25795. }
  25796. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25797. return;
  25798. }
  25799. _this._pointerCaptures[evt.pointerId] = true;
  25800. _this._startingPointerPosition.x = _this._pointerX;
  25801. _this._startingPointerPosition.y = _this._pointerY;
  25802. _this._startingPointerTime = Date.now();
  25803. if (!_this.pointerDownPredicate) {
  25804. _this.pointerDownPredicate = function (mesh) {
  25805. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25806. };
  25807. }
  25808. // Meshes
  25809. _this._pickedDownMesh = null;
  25810. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25811. _this._processPointerDown(pickResult, evt);
  25812. // Sprites
  25813. _this._pickedDownSprite = null;
  25814. if (_this.spriteManagers.length > 0) {
  25815. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25816. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25817. if (pickResult.pickedSprite.actionManager) {
  25818. _this._pickedDownSprite = pickResult.pickedSprite;
  25819. switch (evt.button) {
  25820. case 0:
  25821. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25822. break;
  25823. case 1:
  25824. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25825. break;
  25826. case 2:
  25827. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25828. break;
  25829. }
  25830. if (pickResult.pickedSprite.actionManager) {
  25831. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25832. }
  25833. }
  25834. }
  25835. }
  25836. };
  25837. this._onPointerUp = function (evt) {
  25838. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25839. return; // So we need to test it the pointer down was pressed before.
  25840. }
  25841. _this._totalPointersPressed--;
  25842. _this._pickedUpMesh = null;
  25843. _this._meshPickProceed = false;
  25844. _this._updatePointerPosition(evt);
  25845. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25846. // PreObservable support
  25847. if (_this.onPrePointerObservable.hasObservers()) {
  25848. if (!clickInfo.ignore) {
  25849. if (!clickInfo.hasSwiped) {
  25850. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25851. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25852. return;
  25853. }
  25854. }
  25855. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25856. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25857. return;
  25858. }
  25859. }
  25860. }
  25861. }
  25862. else {
  25863. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25864. return;
  25865. }
  25866. }
  25867. }
  25868. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25869. return;
  25870. }
  25871. _this._pointerCaptures[evt.pointerId] = false;
  25872. if (!_this.pointerUpPredicate) {
  25873. _this.pointerUpPredicate = function (mesh) {
  25874. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25875. };
  25876. }
  25877. // Meshes
  25878. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25879. _this._initActionManager(null, clickInfo);
  25880. }
  25881. if (!pickResult) {
  25882. pickResult = _this._currentPickResult;
  25883. }
  25884. _this._processPointerUp(pickResult, evt, clickInfo);
  25885. // Sprites
  25886. if (!clickInfo.ignore) {
  25887. if (_this.spriteManagers.length > 0) {
  25888. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25889. if (spritePickResult) {
  25890. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25891. if (spritePickResult.pickedSprite.actionManager) {
  25892. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25893. if (spritePickResult.pickedSprite.actionManager) {
  25894. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25895. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25896. }
  25897. }
  25898. }
  25899. }
  25900. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25901. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25902. }
  25903. }
  25904. }
  25905. }
  25906. _this._previousPickResult = _this._currentPickResult;
  25907. });
  25908. };
  25909. this._onKeyDown = function (evt) {
  25910. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25911. if (_this.onPreKeyboardObservable.hasObservers()) {
  25912. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25913. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25914. if (pi.skipOnPointerObservable) {
  25915. return;
  25916. }
  25917. }
  25918. if (_this.onKeyboardObservable.hasObservers()) {
  25919. var pi = new BABYLON.KeyboardInfo(type, evt);
  25920. _this.onKeyboardObservable.notifyObservers(pi, type);
  25921. }
  25922. if (_this.actionManager) {
  25923. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25924. }
  25925. };
  25926. this._onKeyUp = function (evt) {
  25927. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25928. if (_this.onPreKeyboardObservable.hasObservers()) {
  25929. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25930. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25931. if (pi.skipOnPointerObservable) {
  25932. return;
  25933. }
  25934. }
  25935. if (_this.onKeyboardObservable.hasObservers()) {
  25936. var pi = new BABYLON.KeyboardInfo(type, evt);
  25937. _this.onKeyboardObservable.notifyObservers(pi, type);
  25938. }
  25939. if (_this.actionManager) {
  25940. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25941. }
  25942. };
  25943. var engine = this.getEngine();
  25944. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25945. if (!canvas) {
  25946. return;
  25947. }
  25948. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25949. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25950. });
  25951. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25952. if (!canvas) {
  25953. return;
  25954. }
  25955. canvas.removeEventListener("keydown", _this._onKeyDown);
  25956. canvas.removeEventListener("keyup", _this._onKeyUp);
  25957. });
  25958. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25959. var canvas = this._engine.getRenderingCanvas();
  25960. if (!canvas) {
  25961. return;
  25962. }
  25963. if (attachMove) {
  25964. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25965. // Wheel
  25966. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25967. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25968. }
  25969. if (attachDown) {
  25970. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25971. }
  25972. if (attachUp) {
  25973. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25974. }
  25975. canvas.tabIndex = 1;
  25976. };
  25977. /** Detaches all event handlers*/
  25978. Scene.prototype.detachControl = function () {
  25979. var engine = this.getEngine();
  25980. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25981. var canvas = engine.getRenderingCanvas();
  25982. if (!canvas) {
  25983. return;
  25984. }
  25985. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25986. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25987. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25988. if (this._onCanvasBlurObserver) {
  25989. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25990. }
  25991. if (this._onCanvasFocusObserver) {
  25992. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25993. }
  25994. // Wheel
  25995. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25996. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25997. // Keyboard
  25998. canvas.removeEventListener("keydown", this._onKeyDown);
  25999. canvas.removeEventListener("keyup", this._onKeyUp);
  26000. // Observables
  26001. this.onKeyboardObservable.clear();
  26002. this.onPreKeyboardObservable.clear();
  26003. this.onPointerObservable.clear();
  26004. this.onPrePointerObservable.clear();
  26005. };
  26006. /**
  26007. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26008. * Delay loaded resources are not taking in account
  26009. * @return true if all required resources are ready
  26010. */
  26011. Scene.prototype.isReady = function () {
  26012. if (this._isDisposed) {
  26013. return false;
  26014. }
  26015. if (this._pendingData.length > 0) {
  26016. return false;
  26017. }
  26018. var index;
  26019. var engine = this.getEngine();
  26020. // Geometries
  26021. for (index = 0; index < this.geometries.length; index++) {
  26022. var geometry = this.geometries[index];
  26023. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26024. return false;
  26025. }
  26026. }
  26027. // Meshes
  26028. for (index = 0; index < this.meshes.length; index++) {
  26029. var mesh = this.meshes[index];
  26030. if (!mesh.isEnabled()) {
  26031. continue;
  26032. }
  26033. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26034. continue;
  26035. }
  26036. if (!mesh.isReady(true)) {
  26037. return false;
  26038. }
  26039. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26040. // Is Ready For Mesh
  26041. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26042. var step = _a[_i];
  26043. if (!step.action(mesh, hardwareInstancedRendering)) {
  26044. return false;
  26045. }
  26046. }
  26047. }
  26048. // Post-processes
  26049. if (this.activeCameras && this.activeCameras.length > 0) {
  26050. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26051. var camera = _c[_b];
  26052. if (!camera.isReady(true)) {
  26053. return false;
  26054. }
  26055. }
  26056. }
  26057. else if (this.activeCamera) {
  26058. if (!this.activeCamera.isReady(true)) {
  26059. return false;
  26060. }
  26061. }
  26062. // Particles
  26063. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26064. var particleSystem = _e[_d];
  26065. if (!particleSystem.isReady()) {
  26066. return false;
  26067. }
  26068. }
  26069. return true;
  26070. };
  26071. /** Resets all cached information relative to material (including effect and visibility) */
  26072. Scene.prototype.resetCachedMaterial = function () {
  26073. this._cachedMaterial = null;
  26074. this._cachedEffect = null;
  26075. this._cachedVisibility = null;
  26076. };
  26077. /**
  26078. * Registers a function to be called before every frame render
  26079. * @param func defines the function to register
  26080. */
  26081. Scene.prototype.registerBeforeRender = function (func) {
  26082. this.onBeforeRenderObservable.add(func);
  26083. };
  26084. /**
  26085. * Unregisters a function called before every frame render
  26086. * @param func defines the function to unregister
  26087. */
  26088. Scene.prototype.unregisterBeforeRender = function (func) {
  26089. this.onBeforeRenderObservable.removeCallback(func);
  26090. };
  26091. /**
  26092. * Registers a function to be called after every frame render
  26093. * @param func defines the function to register
  26094. */
  26095. Scene.prototype.registerAfterRender = function (func) {
  26096. this.onAfterRenderObservable.add(func);
  26097. };
  26098. /**
  26099. * Unregisters a function called after every frame render
  26100. * @param func defines the function to unregister
  26101. */
  26102. Scene.prototype.unregisterAfterRender = function (func) {
  26103. this.onAfterRenderObservable.removeCallback(func);
  26104. };
  26105. Scene.prototype._executeOnceBeforeRender = function (func) {
  26106. var _this = this;
  26107. var execFunc = function () {
  26108. func();
  26109. setTimeout(function () {
  26110. _this.unregisterBeforeRender(execFunc);
  26111. });
  26112. };
  26113. this.registerBeforeRender(execFunc);
  26114. };
  26115. /**
  26116. * The provided function will run before render once and will be disposed afterwards.
  26117. * A timeout delay can be provided so that the function will be executed in N ms.
  26118. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26119. * @param func The function to be executed.
  26120. * @param timeout optional delay in ms
  26121. */
  26122. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26123. var _this = this;
  26124. if (timeout !== undefined) {
  26125. setTimeout(function () {
  26126. _this._executeOnceBeforeRender(func);
  26127. }, timeout);
  26128. }
  26129. else {
  26130. this._executeOnceBeforeRender(func);
  26131. }
  26132. };
  26133. /** @hidden */
  26134. Scene.prototype._addPendingData = function (data) {
  26135. this._pendingData.push(data);
  26136. };
  26137. /** @hidden */
  26138. Scene.prototype._removePendingData = function (data) {
  26139. var wasLoading = this.isLoading;
  26140. var index = this._pendingData.indexOf(data);
  26141. if (index !== -1) {
  26142. this._pendingData.splice(index, 1);
  26143. }
  26144. if (wasLoading && !this.isLoading) {
  26145. this.onDataLoadedObservable.notifyObservers(this);
  26146. }
  26147. };
  26148. /**
  26149. * Returns the number of items waiting to be loaded
  26150. * @returns the number of items waiting to be loaded
  26151. */
  26152. Scene.prototype.getWaitingItemsCount = function () {
  26153. return this._pendingData.length;
  26154. };
  26155. Object.defineProperty(Scene.prototype, "isLoading", {
  26156. /**
  26157. * Returns a boolean indicating if the scene is still loading data
  26158. */
  26159. get: function () {
  26160. return this._pendingData.length > 0;
  26161. },
  26162. enumerable: true,
  26163. configurable: true
  26164. });
  26165. /**
  26166. * Registers a function to be executed when the scene is ready
  26167. * @param {Function} func - the function to be executed
  26168. */
  26169. Scene.prototype.executeWhenReady = function (func) {
  26170. var _this = this;
  26171. this.onReadyObservable.add(func);
  26172. if (this._executeWhenReadyTimeoutId !== -1) {
  26173. return;
  26174. }
  26175. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26176. _this._checkIsReady();
  26177. }, 150);
  26178. };
  26179. /**
  26180. * Returns a promise that resolves when the scene is ready
  26181. * @returns A promise that resolves when the scene is ready
  26182. */
  26183. Scene.prototype.whenReadyAsync = function () {
  26184. var _this = this;
  26185. return new Promise(function (resolve) {
  26186. _this.executeWhenReady(function () {
  26187. resolve();
  26188. });
  26189. });
  26190. };
  26191. /** @hidden */
  26192. Scene.prototype._checkIsReady = function () {
  26193. var _this = this;
  26194. this._registerTransientComponents();
  26195. if (this.isReady()) {
  26196. this.onReadyObservable.notifyObservers(this);
  26197. this.onReadyObservable.clear();
  26198. this._executeWhenReadyTimeoutId = -1;
  26199. return;
  26200. }
  26201. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26202. _this._checkIsReady();
  26203. }, 150);
  26204. };
  26205. // Animations
  26206. /**
  26207. * Will start the animation sequence of a given target
  26208. * @param target defines the target
  26209. * @param from defines from which frame should animation start
  26210. * @param to defines until which frame should animation run.
  26211. * @param weight defines the weight to apply to the animation (1.0 by default)
  26212. * @param loop defines if the animation loops
  26213. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26214. * @param onAnimationEnd defines the function to be executed when the animation ends
  26215. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26216. * @returns the animatable object created for this animation
  26217. */
  26218. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  26219. if (weight === void 0) { weight = 1.0; }
  26220. if (speedRatio === void 0) { speedRatio = 1.0; }
  26221. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  26222. returnedAnimatable.weight = weight;
  26223. return returnedAnimatable;
  26224. };
  26225. /**
  26226. * Will start the animation sequence of a given target
  26227. * @param target defines the target
  26228. * @param from defines from which frame should animation start
  26229. * @param to defines until which frame should animation run.
  26230. * @param loop defines if the animation loops
  26231. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26232. * @param onAnimationEnd defines the function to be executed when the animation ends
  26233. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26234. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26235. * @returns the animatable object created for this animation
  26236. */
  26237. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26238. if (speedRatio === void 0) { speedRatio = 1.0; }
  26239. if (stopCurrent === void 0) { stopCurrent = true; }
  26240. if (from > to && speedRatio > 0) {
  26241. speedRatio *= -1;
  26242. }
  26243. if (stopCurrent) {
  26244. this.stopAnimation(target);
  26245. }
  26246. if (!animatable) {
  26247. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26248. }
  26249. // Local animations
  26250. if (target.animations) {
  26251. animatable.appendAnimations(target, target.animations);
  26252. }
  26253. // Children animations
  26254. if (target.getAnimatables) {
  26255. var animatables = target.getAnimatables();
  26256. for (var index = 0; index < animatables.length; index++) {
  26257. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26258. }
  26259. }
  26260. animatable.reset();
  26261. return animatable;
  26262. };
  26263. /**
  26264. * Begin a new animation on a given node
  26265. * @param target defines the target where the animation will take place
  26266. * @param animations defines the list of animations to start
  26267. * @param from defines the initial value
  26268. * @param to defines the final value
  26269. * @param loop defines if you want animation to loop (off by default)
  26270. * @param speedRatio defines the speed ratio to apply to all animations
  26271. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26272. * @returns the list of created animatables
  26273. */
  26274. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26275. if (speedRatio === undefined) {
  26276. speedRatio = 1.0;
  26277. }
  26278. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26279. return animatable;
  26280. };
  26281. /**
  26282. * Begin a new animation on a given node and its hierarchy
  26283. * @param target defines the root node where the animation will take place
  26284. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  26285. * @param animations defines the list of animations to start
  26286. * @param from defines the initial value
  26287. * @param to defines the final value
  26288. * @param loop defines if you want animation to loop (off by default)
  26289. * @param speedRatio defines the speed ratio to apply to all animations
  26290. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26291. * @returns the list of animatables created for all nodes
  26292. */
  26293. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26294. var children = target.getDescendants(directDescendantsOnly);
  26295. var result = [];
  26296. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26297. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26298. var child = children_1[_i];
  26299. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26300. }
  26301. return result;
  26302. };
  26303. /**
  26304. * Gets the animatable associated with a specific target
  26305. * @param target defines the target of the animatable
  26306. * @returns the required animatable if found
  26307. */
  26308. Scene.prototype.getAnimatableByTarget = function (target) {
  26309. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26310. if (this._activeAnimatables[index].target === target) {
  26311. return this._activeAnimatables[index];
  26312. }
  26313. }
  26314. return null;
  26315. };
  26316. /**
  26317. * Gets all animatables associated with a given target
  26318. * @param target defines the target to look animatables for
  26319. * @returns an array of Animatables
  26320. */
  26321. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26322. var result = [];
  26323. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26324. if (this._activeAnimatables[index].target === target) {
  26325. result.push(this._activeAnimatables[index]);
  26326. }
  26327. }
  26328. return result;
  26329. };
  26330. Object.defineProperty(Scene.prototype, "animatables", {
  26331. /**
  26332. * Gets all animatable attached to the scene
  26333. */
  26334. get: function () {
  26335. return this._activeAnimatables;
  26336. },
  26337. enumerable: true,
  26338. configurable: true
  26339. });
  26340. /**
  26341. * Will stop the animation of the given target
  26342. * @param target - the target
  26343. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26344. */
  26345. Scene.prototype.stopAnimation = function (target, animationName) {
  26346. var animatables = this.getAllAnimatablesByTarget(target);
  26347. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26348. var animatable = animatables_1[_i];
  26349. animatable.stop(animationName);
  26350. }
  26351. };
  26352. /**
  26353. * Stops and removes all animations that have been applied to the scene
  26354. */
  26355. Scene.prototype.stopAllAnimations = function () {
  26356. if (this._activeAnimatables) {
  26357. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26358. this._activeAnimatables[i].stop();
  26359. }
  26360. this._activeAnimatables = [];
  26361. }
  26362. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26363. var group = _a[_i];
  26364. group.stop();
  26365. }
  26366. };
  26367. Scene.prototype._animate = function () {
  26368. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26369. return;
  26370. }
  26371. // Getting time
  26372. var now = BABYLON.Tools.Now;
  26373. if (!this._animationTimeLast) {
  26374. if (this._pendingData.length > 0) {
  26375. return;
  26376. }
  26377. this._animationTimeLast = now;
  26378. }
  26379. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26380. this._animationTime += deltaTime;
  26381. this._animationTimeLast = now;
  26382. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26383. this._activeAnimatables[index]._animate(this._animationTime);
  26384. }
  26385. // Late animation bindings
  26386. this._processLateAnimationBindings();
  26387. };
  26388. /** @hidden */
  26389. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26390. var target = runtimeAnimation.target;
  26391. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26392. if (!target._lateAnimationHolders) {
  26393. target._lateAnimationHolders = {};
  26394. }
  26395. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26396. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26397. totalWeight: 0,
  26398. animations: [],
  26399. originalValue: originalValue
  26400. };
  26401. }
  26402. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26403. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26404. };
  26405. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26406. var normalizer = 1.0;
  26407. var finalPosition = BABYLON.Tmp.Vector3[0];
  26408. var finalScaling = BABYLON.Tmp.Vector3[1];
  26409. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26410. var startIndex = 0;
  26411. var originalAnimation = holder.animations[0];
  26412. var originalValue = holder.originalValue;
  26413. var scale = 1;
  26414. if (holder.totalWeight < 1.0) {
  26415. // We need to mix the original value in
  26416. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26417. scale = 1.0 - holder.totalWeight;
  26418. }
  26419. else {
  26420. startIndex = 1;
  26421. // We need to normalize the weights
  26422. normalizer = holder.totalWeight;
  26423. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26424. scale = originalAnimation.weight / normalizer;
  26425. if (scale == 1) {
  26426. return originalAnimation.currentValue;
  26427. }
  26428. }
  26429. finalScaling.scaleInPlace(scale);
  26430. finalPosition.scaleInPlace(scale);
  26431. finalQuaternion.scaleInPlace(scale);
  26432. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26433. var runtimeAnimation = holder.animations[animIndex];
  26434. var scale = runtimeAnimation.weight / normalizer;
  26435. var currentPosition = BABYLON.Tmp.Vector3[2];
  26436. var currentScaling = BABYLON.Tmp.Vector3[3];
  26437. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26438. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26439. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26440. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26441. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26442. }
  26443. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26444. return originalAnimation._workValue;
  26445. };
  26446. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26447. var originalAnimation = holder.animations[0];
  26448. var originalValue = holder.originalValue;
  26449. if (holder.animations.length === 1) {
  26450. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26451. }
  26452. var normalizer = 1.0;
  26453. var quaternions;
  26454. var weights;
  26455. if (holder.totalWeight < 1.0) {
  26456. var scale = 1.0 - holder.totalWeight;
  26457. quaternions = [];
  26458. weights = [];
  26459. quaternions.push(originalValue);
  26460. weights.push(scale);
  26461. }
  26462. else {
  26463. if (holder.animations.length === 2) { // Slerp as soon as we can
  26464. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26465. }
  26466. quaternions = [];
  26467. weights = [];
  26468. normalizer = holder.totalWeight;
  26469. }
  26470. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26471. var runtimeAnimation = holder.animations[animIndex];
  26472. quaternions.push(runtimeAnimation.currentValue);
  26473. weights.push(runtimeAnimation.weight / normalizer);
  26474. }
  26475. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26476. var cumulativeAmount = 0;
  26477. var cumulativeQuaternion = null;
  26478. for (var index = 0; index < quaternions.length;) {
  26479. if (!cumulativeQuaternion) {
  26480. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26481. cumulativeAmount = weights[index] + weights[index + 1];
  26482. index += 2;
  26483. continue;
  26484. }
  26485. cumulativeAmount += weights[index];
  26486. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26487. index++;
  26488. }
  26489. return cumulativeQuaternion;
  26490. };
  26491. Scene.prototype._processLateAnimationBindings = function () {
  26492. if (!this._registeredForLateAnimationBindings.length) {
  26493. return;
  26494. }
  26495. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26496. var target = this._registeredForLateAnimationBindings.data[index];
  26497. for (var path in target._lateAnimationHolders) {
  26498. var holder = target._lateAnimationHolders[path];
  26499. var originalAnimation = holder.animations[0];
  26500. var originalValue = holder.originalValue;
  26501. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26502. var finalValue = void 0;
  26503. if (matrixDecomposeMode) {
  26504. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26505. }
  26506. else {
  26507. var quaternionMode = originalValue.w !== undefined;
  26508. if (quaternionMode) {
  26509. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26510. }
  26511. else {
  26512. var startIndex = 0;
  26513. var normalizer = 1.0;
  26514. if (holder.totalWeight < 1.0) {
  26515. // We need to mix the original value in
  26516. if (originalValue.scale) {
  26517. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26518. }
  26519. else {
  26520. finalValue = originalValue * (1.0 - holder.totalWeight);
  26521. }
  26522. }
  26523. else {
  26524. // We need to normalize the weights
  26525. normalizer = holder.totalWeight;
  26526. var scale_1 = originalAnimation.weight / normalizer;
  26527. if (scale_1 !== 1) {
  26528. if (originalAnimation.currentValue.scale) {
  26529. finalValue = originalAnimation.currentValue.scale(scale_1);
  26530. }
  26531. else {
  26532. finalValue = originalAnimation.currentValue * scale_1;
  26533. }
  26534. }
  26535. else {
  26536. finalValue = originalAnimation.currentValue;
  26537. }
  26538. startIndex = 1;
  26539. }
  26540. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26541. var runtimeAnimation = holder.animations[animIndex];
  26542. var scale = runtimeAnimation.weight / normalizer;
  26543. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26544. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26545. }
  26546. else {
  26547. finalValue += runtimeAnimation.currentValue * scale;
  26548. }
  26549. }
  26550. }
  26551. }
  26552. target[path] = finalValue;
  26553. }
  26554. target._lateAnimationHolders = {};
  26555. }
  26556. this._registeredForLateAnimationBindings.reset();
  26557. };
  26558. // Matrix
  26559. /** @hidden */
  26560. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26561. this._useAlternateCameraConfiguration = active;
  26562. };
  26563. /**
  26564. * Gets the current view matrix
  26565. * @returns a Matrix
  26566. */
  26567. Scene.prototype.getViewMatrix = function () {
  26568. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26569. };
  26570. /**
  26571. * Gets the current projection matrix
  26572. * @returns a Matrix
  26573. */
  26574. Scene.prototype.getProjectionMatrix = function () {
  26575. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26576. };
  26577. /**
  26578. * Gets the current transform matrix
  26579. * @returns a Matrix made of View * Projection
  26580. */
  26581. Scene.prototype.getTransformMatrix = function () {
  26582. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26583. };
  26584. /**
  26585. * Sets the current transform matrix
  26586. * @param view defines the View matrix to use
  26587. * @param projection defines the Projection matrix to use
  26588. */
  26589. Scene.prototype.setTransformMatrix = function (view, projection) {
  26590. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26591. return;
  26592. }
  26593. this._viewUpdateFlag = view.updateFlag;
  26594. this._projectionUpdateFlag = projection.updateFlag;
  26595. this._viewMatrix = view;
  26596. this._projectionMatrix = projection;
  26597. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26598. // Update frustum
  26599. if (!this._frustumPlanes) {
  26600. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26601. }
  26602. else {
  26603. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26604. }
  26605. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26606. var otherCamera = this.activeCamera._alternateCamera;
  26607. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26608. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26609. }
  26610. if (this._sceneUbo.useUbo) {
  26611. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26612. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26613. this._sceneUbo.update();
  26614. }
  26615. };
  26616. /** @hidden */
  26617. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26618. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26619. return;
  26620. }
  26621. this._alternateViewUpdateFlag = view.updateFlag;
  26622. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26623. this._alternateViewMatrix = view;
  26624. this._alternateProjectionMatrix = projection;
  26625. if (!this._alternateTransformMatrix) {
  26626. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26627. }
  26628. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26629. if (!this._alternateSceneUbo) {
  26630. this._createAlternateUbo();
  26631. }
  26632. if (this._alternateSceneUbo.useUbo) {
  26633. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26634. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26635. this._alternateSceneUbo.update();
  26636. }
  26637. };
  26638. /**
  26639. * Gets the uniform buffer used to store scene data
  26640. * @returns a UniformBuffer
  26641. */
  26642. Scene.prototype.getSceneUniformBuffer = function () {
  26643. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26644. };
  26645. /**
  26646. * Gets an unique (relatively to the current scene) Id
  26647. * @returns an unique number for the scene
  26648. */
  26649. Scene.prototype.getUniqueId = function () {
  26650. var result = Scene._uniqueIdCounter;
  26651. Scene._uniqueIdCounter++;
  26652. return result;
  26653. };
  26654. /**
  26655. * Add a mesh to the list of scene's meshes
  26656. * @param newMesh defines the mesh to add
  26657. * @param recursive if all child meshes should also be added to the scene
  26658. */
  26659. Scene.prototype.addMesh = function (newMesh, recursive) {
  26660. var _this = this;
  26661. if (recursive === void 0) { recursive = false; }
  26662. this.meshes.push(newMesh);
  26663. //notify the collision coordinator
  26664. if (this.collisionCoordinator) {
  26665. this.collisionCoordinator.onMeshAdded(newMesh);
  26666. }
  26667. newMesh._resyncLightSources();
  26668. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26669. if (recursive) {
  26670. newMesh.getChildMeshes().forEach(function (m) {
  26671. _this.addMesh(m);
  26672. });
  26673. }
  26674. };
  26675. /**
  26676. * Remove a mesh for the list of scene's meshes
  26677. * @param toRemove defines the mesh to remove
  26678. * @param recursive if all child meshes should also be removed from the scene
  26679. * @returns the index where the mesh was in the mesh list
  26680. */
  26681. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26682. var _this = this;
  26683. if (recursive === void 0) { recursive = false; }
  26684. var index = this.meshes.indexOf(toRemove);
  26685. if (index !== -1) {
  26686. // Remove from the scene if mesh found
  26687. this.meshes.splice(index, 1);
  26688. }
  26689. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26690. if (recursive) {
  26691. toRemove.getChildMeshes().forEach(function (m) {
  26692. _this.removeMesh(m);
  26693. });
  26694. }
  26695. return index;
  26696. };
  26697. /**
  26698. * Add a transform node to the list of scene's transform nodes
  26699. * @param newTransformNode defines the transform node to add
  26700. */
  26701. Scene.prototype.addTransformNode = function (newTransformNode) {
  26702. this.transformNodes.push(newTransformNode);
  26703. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26704. };
  26705. /**
  26706. * Remove a transform node for the list of scene's transform nodes
  26707. * @param toRemove defines the transform node to remove
  26708. * @returns the index where the transform node was in the transform node list
  26709. */
  26710. Scene.prototype.removeTransformNode = function (toRemove) {
  26711. var index = this.transformNodes.indexOf(toRemove);
  26712. if (index !== -1) {
  26713. // Remove from the scene if found
  26714. this.transformNodes.splice(index, 1);
  26715. }
  26716. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26717. return index;
  26718. };
  26719. /**
  26720. * Remove a skeleton for the list of scene's skeletons
  26721. * @param toRemove defines the skeleton to remove
  26722. * @returns the index where the skeleton was in the skeleton list
  26723. */
  26724. Scene.prototype.removeSkeleton = function (toRemove) {
  26725. var index = this.skeletons.indexOf(toRemove);
  26726. if (index !== -1) {
  26727. // Remove from the scene if found
  26728. this.skeletons.splice(index, 1);
  26729. }
  26730. return index;
  26731. };
  26732. /**
  26733. * Remove a morph target for the list of scene's morph targets
  26734. * @param toRemove defines the morph target to remove
  26735. * @returns the index where the morph target was in the morph target list
  26736. */
  26737. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26738. var index = this.morphTargetManagers.indexOf(toRemove);
  26739. if (index !== -1) {
  26740. // Remove from the scene if found
  26741. this.morphTargetManagers.splice(index, 1);
  26742. }
  26743. return index;
  26744. };
  26745. /**
  26746. * Remove a light for the list of scene's lights
  26747. * @param toRemove defines the light to remove
  26748. * @returns the index where the light was in the light list
  26749. */
  26750. Scene.prototype.removeLight = function (toRemove) {
  26751. var index = this.lights.indexOf(toRemove);
  26752. if (index !== -1) {
  26753. // Remove from meshes
  26754. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26755. var mesh = _a[_i];
  26756. mesh._removeLightSource(toRemove);
  26757. }
  26758. // Remove from the scene if mesh found
  26759. this.lights.splice(index, 1);
  26760. this.sortLightsByPriority();
  26761. }
  26762. this.onLightRemovedObservable.notifyObservers(toRemove);
  26763. return index;
  26764. };
  26765. /**
  26766. * Remove a camera for the list of scene's cameras
  26767. * @param toRemove defines the camera to remove
  26768. * @returns the index where the camera was in the camera list
  26769. */
  26770. Scene.prototype.removeCamera = function (toRemove) {
  26771. var index = this.cameras.indexOf(toRemove);
  26772. if (index !== -1) {
  26773. // Remove from the scene if mesh found
  26774. this.cameras.splice(index, 1);
  26775. }
  26776. // Remove from activeCameras
  26777. var index2 = this.activeCameras.indexOf(toRemove);
  26778. if (index2 !== -1) {
  26779. // Remove from the scene if mesh found
  26780. this.activeCameras.splice(index2, 1);
  26781. }
  26782. // Reset the activeCamera
  26783. if (this.activeCamera === toRemove) {
  26784. if (this.cameras.length > 0) {
  26785. this.activeCamera = this.cameras[0];
  26786. }
  26787. else {
  26788. this.activeCamera = null;
  26789. }
  26790. }
  26791. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26792. return index;
  26793. };
  26794. /**
  26795. * Remove a particle system for the list of scene's particle systems
  26796. * @param toRemove defines the particle system to remove
  26797. * @returns the index where the particle system was in the particle system list
  26798. */
  26799. Scene.prototype.removeParticleSystem = function (toRemove) {
  26800. var index = this.particleSystems.indexOf(toRemove);
  26801. if (index !== -1) {
  26802. this.particleSystems.splice(index, 1);
  26803. }
  26804. return index;
  26805. };
  26806. /**
  26807. * Remove a animation for the list of scene's animations
  26808. * @param toRemove defines the animation to remove
  26809. * @returns the index where the animation was in the animation list
  26810. */
  26811. Scene.prototype.removeAnimation = function (toRemove) {
  26812. var index = this.animations.indexOf(toRemove);
  26813. if (index !== -1) {
  26814. this.animations.splice(index, 1);
  26815. }
  26816. return index;
  26817. };
  26818. /**
  26819. * Removes the given animation group from this scene.
  26820. * @param toRemove The animation group to remove
  26821. * @returns The index of the removed animation group
  26822. */
  26823. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26824. var index = this.animationGroups.indexOf(toRemove);
  26825. if (index !== -1) {
  26826. this.animationGroups.splice(index, 1);
  26827. }
  26828. return index;
  26829. };
  26830. /**
  26831. * Removes the given multi-material from this scene.
  26832. * @param toRemove The multi-material to remove
  26833. * @returns The index of the removed multi-material
  26834. */
  26835. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26836. var index = this.multiMaterials.indexOf(toRemove);
  26837. if (index !== -1) {
  26838. this.multiMaterials.splice(index, 1);
  26839. }
  26840. return index;
  26841. };
  26842. /**
  26843. * Removes the given material from this scene.
  26844. * @param toRemove The material to remove
  26845. * @returns The index of the removed material
  26846. */
  26847. Scene.prototype.removeMaterial = function (toRemove) {
  26848. var index = this.materials.indexOf(toRemove);
  26849. if (index !== -1) {
  26850. this.materials.splice(index, 1);
  26851. }
  26852. return index;
  26853. };
  26854. /**
  26855. * Removes the given action manager from this scene.
  26856. * @param toRemove The action manager to remove
  26857. * @returns The index of the removed action manager
  26858. */
  26859. Scene.prototype.removeActionManager = function (toRemove) {
  26860. var index = this.actionManagers.indexOf(toRemove);
  26861. if (index !== -1) {
  26862. this.actionManagers.splice(index, 1);
  26863. }
  26864. return index;
  26865. };
  26866. /**
  26867. * Removes the given texture from this scene.
  26868. * @param toRemove The texture to remove
  26869. * @returns The index of the removed texture
  26870. */
  26871. Scene.prototype.removeTexture = function (toRemove) {
  26872. var index = this.textures.indexOf(toRemove);
  26873. if (index !== -1) {
  26874. this.textures.splice(index, 1);
  26875. }
  26876. return index;
  26877. };
  26878. /**
  26879. * Adds the given light to this scene
  26880. * @param newLight The light to add
  26881. */
  26882. Scene.prototype.addLight = function (newLight) {
  26883. this.lights.push(newLight);
  26884. this.sortLightsByPriority();
  26885. // Add light to all meshes (To support if the light is removed and then readded)
  26886. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26887. var mesh = _a[_i];
  26888. if (mesh._lightSources.indexOf(newLight) === -1) {
  26889. mesh._lightSources.push(newLight);
  26890. mesh._resyncLightSources();
  26891. }
  26892. }
  26893. this.onNewLightAddedObservable.notifyObservers(newLight);
  26894. };
  26895. /**
  26896. * Sorts the list list based on light priorities
  26897. */
  26898. Scene.prototype.sortLightsByPriority = function () {
  26899. if (this.requireLightSorting) {
  26900. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26901. }
  26902. };
  26903. /**
  26904. * Adds the given camera to this scene
  26905. * @param newCamera The camera to add
  26906. */
  26907. Scene.prototype.addCamera = function (newCamera) {
  26908. this.cameras.push(newCamera);
  26909. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26910. };
  26911. /**
  26912. * Adds the given skeleton to this scene
  26913. * @param newSkeleton The skeleton to add
  26914. */
  26915. Scene.prototype.addSkeleton = function (newSkeleton) {
  26916. this.skeletons.push(newSkeleton);
  26917. };
  26918. /**
  26919. * Adds the given particle system to this scene
  26920. * @param newParticleSystem The particle system to add
  26921. */
  26922. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26923. this.particleSystems.push(newParticleSystem);
  26924. };
  26925. /**
  26926. * Adds the given animation to this scene
  26927. * @param newAnimation The animation to add
  26928. */
  26929. Scene.prototype.addAnimation = function (newAnimation) {
  26930. this.animations.push(newAnimation);
  26931. };
  26932. /**
  26933. * Adds the given animation group to this scene.
  26934. * @param newAnimationGroup The animation group to add
  26935. */
  26936. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26937. this.animationGroups.push(newAnimationGroup);
  26938. };
  26939. /**
  26940. * Adds the given multi-material to this scene
  26941. * @param newMultiMaterial The multi-material to add
  26942. */
  26943. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26944. this.multiMaterials.push(newMultiMaterial);
  26945. };
  26946. /**
  26947. * Adds the given material to this scene
  26948. * @param newMaterial The material to add
  26949. */
  26950. Scene.prototype.addMaterial = function (newMaterial) {
  26951. this.materials.push(newMaterial);
  26952. };
  26953. /**
  26954. * Adds the given morph target to this scene
  26955. * @param newMorphTargetManager The morph target to add
  26956. */
  26957. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26958. this.morphTargetManagers.push(newMorphTargetManager);
  26959. };
  26960. /**
  26961. * Adds the given geometry to this scene
  26962. * @param newGeometry The geometry to add
  26963. */
  26964. Scene.prototype.addGeometry = function (newGeometry) {
  26965. this.geometries.push(newGeometry);
  26966. };
  26967. /**
  26968. * Adds the given action manager to this scene
  26969. * @param newActionManager The action manager to add
  26970. */
  26971. Scene.prototype.addActionManager = function (newActionManager) {
  26972. this.actionManagers.push(newActionManager);
  26973. };
  26974. /**
  26975. * Adds the given texture to this scene.
  26976. * @param newTexture The texture to add
  26977. */
  26978. Scene.prototype.addTexture = function (newTexture) {
  26979. this.textures.push(newTexture);
  26980. };
  26981. /**
  26982. * Switch active camera
  26983. * @param newCamera defines the new active camera
  26984. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26985. */
  26986. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26987. if (attachControl === void 0) { attachControl = true; }
  26988. var canvas = this._engine.getRenderingCanvas();
  26989. if (!canvas) {
  26990. return;
  26991. }
  26992. if (this.activeCamera) {
  26993. this.activeCamera.detachControl(canvas);
  26994. }
  26995. this.activeCamera = newCamera;
  26996. if (attachControl) {
  26997. newCamera.attachControl(canvas);
  26998. }
  26999. };
  27000. /**
  27001. * sets the active camera of the scene using its ID
  27002. * @param id defines the camera's ID
  27003. * @return the new active camera or null if none found.
  27004. */
  27005. Scene.prototype.setActiveCameraByID = function (id) {
  27006. var camera = this.getCameraByID(id);
  27007. if (camera) {
  27008. this.activeCamera = camera;
  27009. return camera;
  27010. }
  27011. return null;
  27012. };
  27013. /**
  27014. * sets the active camera of the scene using its name
  27015. * @param name defines the camera's name
  27016. * @returns the new active camera or null if none found.
  27017. */
  27018. Scene.prototype.setActiveCameraByName = function (name) {
  27019. var camera = this.getCameraByName(name);
  27020. if (camera) {
  27021. this.activeCamera = camera;
  27022. return camera;
  27023. }
  27024. return null;
  27025. };
  27026. /**
  27027. * get an animation group using its name
  27028. * @param name defines the material's name
  27029. * @return the animation group or null if none found.
  27030. */
  27031. Scene.prototype.getAnimationGroupByName = function (name) {
  27032. for (var index = 0; index < this.animationGroups.length; index++) {
  27033. if (this.animationGroups[index].name === name) {
  27034. return this.animationGroups[index];
  27035. }
  27036. }
  27037. return null;
  27038. };
  27039. /**
  27040. * get a material using its id
  27041. * @param id defines the material's ID
  27042. * @return the material or null if none found.
  27043. */
  27044. Scene.prototype.getMaterialByID = function (id) {
  27045. for (var index = 0; index < this.materials.length; index++) {
  27046. if (this.materials[index].id === id) {
  27047. return this.materials[index];
  27048. }
  27049. }
  27050. return null;
  27051. };
  27052. /**
  27053. * Gets a material using its name
  27054. * @param name defines the material's name
  27055. * @return the material or null if none found.
  27056. */
  27057. Scene.prototype.getMaterialByName = function (name) {
  27058. for (var index = 0; index < this.materials.length; index++) {
  27059. if (this.materials[index].name === name) {
  27060. return this.materials[index];
  27061. }
  27062. }
  27063. return null;
  27064. };
  27065. /**
  27066. * Gets a camera using its id
  27067. * @param id defines the id to look for
  27068. * @returns the camera or null if not found
  27069. */
  27070. Scene.prototype.getCameraByID = function (id) {
  27071. for (var index = 0; index < this.cameras.length; index++) {
  27072. if (this.cameras[index].id === id) {
  27073. return this.cameras[index];
  27074. }
  27075. }
  27076. return null;
  27077. };
  27078. /**
  27079. * Gets a camera using its unique id
  27080. * @param uniqueId defines the unique id to look for
  27081. * @returns the camera or null if not found
  27082. */
  27083. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27084. for (var index = 0; index < this.cameras.length; index++) {
  27085. if (this.cameras[index].uniqueId === uniqueId) {
  27086. return this.cameras[index];
  27087. }
  27088. }
  27089. return null;
  27090. };
  27091. /**
  27092. * Gets a camera using its name
  27093. * @param name defines the camera's name
  27094. * @return the camera or null if none found.
  27095. */
  27096. Scene.prototype.getCameraByName = function (name) {
  27097. for (var index = 0; index < this.cameras.length; index++) {
  27098. if (this.cameras[index].name === name) {
  27099. return this.cameras[index];
  27100. }
  27101. }
  27102. return null;
  27103. };
  27104. /**
  27105. * Gets a bone using its id
  27106. * @param id defines the bone's id
  27107. * @return the bone or null if not found
  27108. */
  27109. Scene.prototype.getBoneByID = function (id) {
  27110. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27111. var skeleton = this.skeletons[skeletonIndex];
  27112. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27113. if (skeleton.bones[boneIndex].id === id) {
  27114. return skeleton.bones[boneIndex];
  27115. }
  27116. }
  27117. }
  27118. return null;
  27119. };
  27120. /**
  27121. * Gets a bone using its id
  27122. * @param name defines the bone's name
  27123. * @return the bone or null if not found
  27124. */
  27125. Scene.prototype.getBoneByName = function (name) {
  27126. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27127. var skeleton = this.skeletons[skeletonIndex];
  27128. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27129. if (skeleton.bones[boneIndex].name === name) {
  27130. return skeleton.bones[boneIndex];
  27131. }
  27132. }
  27133. }
  27134. return null;
  27135. };
  27136. /**
  27137. * Gets a light node using its name
  27138. * @param name defines the the light's name
  27139. * @return the light or null if none found.
  27140. */
  27141. Scene.prototype.getLightByName = function (name) {
  27142. for (var index = 0; index < this.lights.length; index++) {
  27143. if (this.lights[index].name === name) {
  27144. return this.lights[index];
  27145. }
  27146. }
  27147. return null;
  27148. };
  27149. /**
  27150. * Gets a light node using its id
  27151. * @param id defines the light's id
  27152. * @return the light or null if none found.
  27153. */
  27154. Scene.prototype.getLightByID = function (id) {
  27155. for (var index = 0; index < this.lights.length; index++) {
  27156. if (this.lights[index].id === id) {
  27157. return this.lights[index];
  27158. }
  27159. }
  27160. return null;
  27161. };
  27162. /**
  27163. * Gets a light node using its scene-generated unique ID
  27164. * @param uniqueId defines the light's unique id
  27165. * @return the light or null if none found.
  27166. */
  27167. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27168. for (var index = 0; index < this.lights.length; index++) {
  27169. if (this.lights[index].uniqueId === uniqueId) {
  27170. return this.lights[index];
  27171. }
  27172. }
  27173. return null;
  27174. };
  27175. /**
  27176. * Gets a particle system by id
  27177. * @param id defines the particle system id
  27178. * @return the corresponding system or null if none found
  27179. */
  27180. Scene.prototype.getParticleSystemByID = function (id) {
  27181. for (var index = 0; index < this.particleSystems.length; index++) {
  27182. if (this.particleSystems[index].id === id) {
  27183. return this.particleSystems[index];
  27184. }
  27185. }
  27186. return null;
  27187. };
  27188. /**
  27189. * Gets a geometry using its ID
  27190. * @param id defines the geometry's id
  27191. * @return the geometry or null if none found.
  27192. */
  27193. Scene.prototype.getGeometryByID = function (id) {
  27194. for (var index = 0; index < this.geometries.length; index++) {
  27195. if (this.geometries[index].id === id) {
  27196. return this.geometries[index];
  27197. }
  27198. }
  27199. return null;
  27200. };
  27201. /**
  27202. * Add a new geometry to this scene
  27203. * @param geometry defines the geometry to be added to the scene.
  27204. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27205. * @return a boolean defining if the geometry was added or not
  27206. */
  27207. Scene.prototype.pushGeometry = function (geometry, force) {
  27208. if (!force && this.getGeometryByID(geometry.id)) {
  27209. return false;
  27210. }
  27211. this.geometries.push(geometry);
  27212. //notify the collision coordinator
  27213. if (this.collisionCoordinator) {
  27214. this.collisionCoordinator.onGeometryAdded(geometry);
  27215. }
  27216. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27217. return true;
  27218. };
  27219. /**
  27220. * Removes an existing geometry
  27221. * @param geometry defines the geometry to be removed from the scene
  27222. * @return a boolean defining if the geometry was removed or not
  27223. */
  27224. Scene.prototype.removeGeometry = function (geometry) {
  27225. var index = this.geometries.indexOf(geometry);
  27226. if (index > -1) {
  27227. this.geometries.splice(index, 1);
  27228. //notify the collision coordinator
  27229. if (this.collisionCoordinator) {
  27230. this.collisionCoordinator.onGeometryDeleted(geometry);
  27231. }
  27232. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27233. return true;
  27234. }
  27235. return false;
  27236. };
  27237. /**
  27238. * Gets the list of geometries attached to the scene
  27239. * @returns an array of Geometry
  27240. */
  27241. Scene.prototype.getGeometries = function () {
  27242. return this.geometries;
  27243. };
  27244. /**
  27245. * Gets the first added mesh found of a given ID
  27246. * @param id defines the id to search for
  27247. * @return the mesh found or null if not found at all
  27248. */
  27249. Scene.prototype.getMeshByID = function (id) {
  27250. for (var index = 0; index < this.meshes.length; index++) {
  27251. if (this.meshes[index].id === id) {
  27252. return this.meshes[index];
  27253. }
  27254. }
  27255. return null;
  27256. };
  27257. /**
  27258. * Gets a list of meshes using their id
  27259. * @param id defines the id to search for
  27260. * @returns a list of meshes
  27261. */
  27262. Scene.prototype.getMeshesByID = function (id) {
  27263. return this.meshes.filter(function (m) {
  27264. return m.id === id;
  27265. });
  27266. };
  27267. /**
  27268. * Gets the first added transform node found of a given ID
  27269. * @param id defines the id to search for
  27270. * @return the found transform node or null if not found at all.
  27271. */
  27272. Scene.prototype.getTransformNodeByID = function (id) {
  27273. for (var index = 0; index < this.transformNodes.length; index++) {
  27274. if (this.transformNodes[index].id === id) {
  27275. return this.transformNodes[index];
  27276. }
  27277. }
  27278. return null;
  27279. };
  27280. /**
  27281. * Gets a list of transform nodes using their id
  27282. * @param id defines the id to search for
  27283. * @returns a list of transform nodes
  27284. */
  27285. Scene.prototype.getTransformNodesByID = function (id) {
  27286. return this.transformNodes.filter(function (m) {
  27287. return m.id === id;
  27288. });
  27289. };
  27290. /**
  27291. * Gets a mesh with its auto-generated unique id
  27292. * @param uniqueId defines the unique id to search for
  27293. * @return the found mesh or null if not found at all.
  27294. */
  27295. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27296. for (var index = 0; index < this.meshes.length; index++) {
  27297. if (this.meshes[index].uniqueId === uniqueId) {
  27298. return this.meshes[index];
  27299. }
  27300. }
  27301. return null;
  27302. };
  27303. /**
  27304. * Gets a the last added mesh using a given id
  27305. * @param id defines the id to search for
  27306. * @return the found mesh or null if not found at all.
  27307. */
  27308. Scene.prototype.getLastMeshByID = function (id) {
  27309. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27310. if (this.meshes[index].id === id) {
  27311. return this.meshes[index];
  27312. }
  27313. }
  27314. return null;
  27315. };
  27316. /**
  27317. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27318. * @param id defines the id to search for
  27319. * @return the found node or null if not found at all
  27320. */
  27321. Scene.prototype.getLastEntryByID = function (id) {
  27322. var index;
  27323. for (index = this.meshes.length - 1; index >= 0; index--) {
  27324. if (this.meshes[index].id === id) {
  27325. return this.meshes[index];
  27326. }
  27327. }
  27328. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27329. if (this.transformNodes[index].id === id) {
  27330. return this.transformNodes[index];
  27331. }
  27332. }
  27333. for (index = this.cameras.length - 1; index >= 0; index--) {
  27334. if (this.cameras[index].id === id) {
  27335. return this.cameras[index];
  27336. }
  27337. }
  27338. for (index = this.lights.length - 1; index >= 0; index--) {
  27339. if (this.lights[index].id === id) {
  27340. return this.lights[index];
  27341. }
  27342. }
  27343. return null;
  27344. };
  27345. /**
  27346. * Gets a node (Mesh, Camera, Light) using a given id
  27347. * @param id defines the id to search for
  27348. * @return the found node or null if not found at all
  27349. */
  27350. Scene.prototype.getNodeByID = function (id) {
  27351. var mesh = this.getMeshByID(id);
  27352. if (mesh) {
  27353. return mesh;
  27354. }
  27355. var light = this.getLightByID(id);
  27356. if (light) {
  27357. return light;
  27358. }
  27359. var camera = this.getCameraByID(id);
  27360. if (camera) {
  27361. return camera;
  27362. }
  27363. var bone = this.getBoneByID(id);
  27364. return bone;
  27365. };
  27366. /**
  27367. * Gets a node (Mesh, Camera, Light) using a given name
  27368. * @param name defines the name to search for
  27369. * @return the found node or null if not found at all.
  27370. */
  27371. Scene.prototype.getNodeByName = function (name) {
  27372. var mesh = this.getMeshByName(name);
  27373. if (mesh) {
  27374. return mesh;
  27375. }
  27376. var light = this.getLightByName(name);
  27377. if (light) {
  27378. return light;
  27379. }
  27380. var camera = this.getCameraByName(name);
  27381. if (camera) {
  27382. return camera;
  27383. }
  27384. var bone = this.getBoneByName(name);
  27385. return bone;
  27386. };
  27387. /**
  27388. * Gets a mesh using a given name
  27389. * @param name defines the name to search for
  27390. * @return the found mesh or null if not found at all.
  27391. */
  27392. Scene.prototype.getMeshByName = function (name) {
  27393. for (var index = 0; index < this.meshes.length; index++) {
  27394. if (this.meshes[index].name === name) {
  27395. return this.meshes[index];
  27396. }
  27397. }
  27398. return null;
  27399. };
  27400. /**
  27401. * Gets a transform node using a given name
  27402. * @param name defines the name to search for
  27403. * @return the found transform node or null if not found at all.
  27404. */
  27405. Scene.prototype.getTransformNodeByName = function (name) {
  27406. for (var index = 0; index < this.transformNodes.length; index++) {
  27407. if (this.transformNodes[index].name === name) {
  27408. return this.transformNodes[index];
  27409. }
  27410. }
  27411. return null;
  27412. };
  27413. /**
  27414. * Gets a sound using a given name
  27415. * @param name defines the name to search for
  27416. * @return the found sound or null if not found at all.
  27417. */
  27418. Scene.prototype.getSoundByName = function (name) {
  27419. var index;
  27420. if (BABYLON.AudioEngine) {
  27421. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27422. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27423. return this.mainSoundTrack.soundCollection[index];
  27424. }
  27425. }
  27426. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27427. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27428. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27429. return this.soundTracks[sdIndex].soundCollection[index];
  27430. }
  27431. }
  27432. }
  27433. }
  27434. return null;
  27435. };
  27436. /**
  27437. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27438. * @param id defines the id to search for
  27439. * @return the found skeleton or null if not found at all.
  27440. */
  27441. Scene.prototype.getLastSkeletonByID = function (id) {
  27442. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27443. if (this.skeletons[index].id === id) {
  27444. return this.skeletons[index];
  27445. }
  27446. }
  27447. return null;
  27448. };
  27449. /**
  27450. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27451. * @param id defines the id to search for
  27452. * @return the found skeleton or null if not found at all.
  27453. */
  27454. Scene.prototype.getSkeletonById = function (id) {
  27455. for (var index = 0; index < this.skeletons.length; index++) {
  27456. if (this.skeletons[index].id === id) {
  27457. return this.skeletons[index];
  27458. }
  27459. }
  27460. return null;
  27461. };
  27462. /**
  27463. * Gets a skeleton using a given name
  27464. * @param name defines the name to search for
  27465. * @return the found skeleton or null if not found at all.
  27466. */
  27467. Scene.prototype.getSkeletonByName = function (name) {
  27468. for (var index = 0; index < this.skeletons.length; index++) {
  27469. if (this.skeletons[index].name === name) {
  27470. return this.skeletons[index];
  27471. }
  27472. }
  27473. return null;
  27474. };
  27475. /**
  27476. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27477. * @param id defines the id to search for
  27478. * @return the found morph target manager or null if not found at all.
  27479. */
  27480. Scene.prototype.getMorphTargetManagerById = function (id) {
  27481. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27482. if (this.morphTargetManagers[index].uniqueId === id) {
  27483. return this.morphTargetManagers[index];
  27484. }
  27485. }
  27486. return null;
  27487. };
  27488. /**
  27489. * Gets a boolean indicating if the given mesh is active
  27490. * @param mesh defines the mesh to look for
  27491. * @returns true if the mesh is in the active list
  27492. */
  27493. Scene.prototype.isActiveMesh = function (mesh) {
  27494. return (this._activeMeshes.indexOf(mesh) !== -1);
  27495. };
  27496. Object.defineProperty(Scene.prototype, "uid", {
  27497. /**
  27498. * Return a unique id as a string which can serve as an identifier for the scene
  27499. */
  27500. get: function () {
  27501. if (!this._uid) {
  27502. this._uid = BABYLON.Tools.RandomId();
  27503. }
  27504. return this._uid;
  27505. },
  27506. enumerable: true,
  27507. configurable: true
  27508. });
  27509. /**
  27510. * Add an externaly attached data from its key.
  27511. * This method call will fail and return false, if such key already exists.
  27512. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27513. * @param key the unique key that identifies the data
  27514. * @param data the data object to associate to the key for this Engine instance
  27515. * @return true if no such key were already present and the data was added successfully, false otherwise
  27516. */
  27517. Scene.prototype.addExternalData = function (key, data) {
  27518. if (!this._externalData) {
  27519. this._externalData = new BABYLON.StringDictionary();
  27520. }
  27521. return this._externalData.add(key, data);
  27522. };
  27523. /**
  27524. * Get an externaly attached data from its key
  27525. * @param key the unique key that identifies the data
  27526. * @return the associated data, if present (can be null), or undefined if not present
  27527. */
  27528. Scene.prototype.getExternalData = function (key) {
  27529. if (!this._externalData) {
  27530. return null;
  27531. }
  27532. return this._externalData.get(key);
  27533. };
  27534. /**
  27535. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27536. * @param key the unique key that identifies the data
  27537. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27538. * @return the associated data, can be null if the factory returned null.
  27539. */
  27540. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27541. if (!this._externalData) {
  27542. this._externalData = new BABYLON.StringDictionary();
  27543. }
  27544. return this._externalData.getOrAddWithFactory(key, factory);
  27545. };
  27546. /**
  27547. * Remove an externaly attached data from the Engine instance
  27548. * @param key the unique key that identifies the data
  27549. * @return true if the data was successfully removed, false if it doesn't exist
  27550. */
  27551. Scene.prototype.removeExternalData = function (key) {
  27552. return this._externalData.remove(key);
  27553. };
  27554. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27555. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27556. if (mesh.showSubMeshesBoundingBox) {
  27557. var boundingInfo = subMesh.getBoundingInfo();
  27558. if (boundingInfo !== null && boundingInfo !== undefined) {
  27559. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27560. }
  27561. }
  27562. var material = subMesh.getMaterial();
  27563. if (material !== null && material !== undefined) {
  27564. // Render targets
  27565. if (material.getRenderTargetTextures !== undefined) {
  27566. if (this._processedMaterials.indexOf(material) === -1) {
  27567. this._processedMaterials.push(material);
  27568. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27569. }
  27570. }
  27571. // Dispatch
  27572. this._activeIndices.addCount(subMesh.indexCount, false);
  27573. this._renderingManager.dispatch(subMesh, mesh, material);
  27574. }
  27575. }
  27576. };
  27577. /**
  27578. * Clear the processed materials smart array preventing retention point in material dispose.
  27579. */
  27580. Scene.prototype.freeProcessedMaterials = function () {
  27581. this._processedMaterials.dispose();
  27582. };
  27583. /**
  27584. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27585. */
  27586. Scene.prototype.freeActiveMeshes = function () {
  27587. this._activeMeshes.dispose();
  27588. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27589. this.activeCamera._activeMeshes.dispose();
  27590. }
  27591. if (this.activeCameras) {
  27592. for (var i = 0; i < this.activeCameras.length; i++) {
  27593. var activeCamera = this.activeCameras[i];
  27594. if (activeCamera && activeCamera._activeMeshes) {
  27595. activeCamera._activeMeshes.dispose();
  27596. }
  27597. }
  27598. }
  27599. };
  27600. /**
  27601. * Clear the info related to rendering groups preventing retention points during dispose.
  27602. */
  27603. Scene.prototype.freeRenderingGroups = function () {
  27604. if (this._renderingManager) {
  27605. this._renderingManager.freeRenderingGroups();
  27606. }
  27607. if (this.textures) {
  27608. for (var i = 0; i < this.textures.length; i++) {
  27609. var texture = this.textures[i];
  27610. if (texture && texture.renderList) {
  27611. texture.freeRenderingGroups();
  27612. }
  27613. }
  27614. }
  27615. };
  27616. /** @hidden */
  27617. Scene.prototype._isInIntermediateRendering = function () {
  27618. return this._intermediateRendering;
  27619. };
  27620. /**
  27621. * Defines the current active mesh candidate provider
  27622. * @param provider defines the provider to use
  27623. */
  27624. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27625. this._activeMeshCandidateProvider = provider;
  27626. };
  27627. /**
  27628. * Gets the current active mesh candidate provider
  27629. * @returns the current active mesh candidate provider
  27630. */
  27631. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27632. return this._activeMeshCandidateProvider;
  27633. };
  27634. /**
  27635. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27636. * @returns the current scene
  27637. */
  27638. Scene.prototype.freezeActiveMeshes = function () {
  27639. if (!this.activeCamera) {
  27640. return this;
  27641. }
  27642. if (!this._frustumPlanes) {
  27643. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27644. }
  27645. this._evaluateActiveMeshes();
  27646. this._activeMeshesFrozen = true;
  27647. return this;
  27648. };
  27649. /**
  27650. * Use this function to restart evaluating active meshes on every frame
  27651. * @returns the current scene
  27652. */
  27653. Scene.prototype.unfreezeActiveMeshes = function () {
  27654. this._activeMeshesFrozen = false;
  27655. return this;
  27656. };
  27657. Scene.prototype._evaluateActiveMeshes = function () {
  27658. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27659. return;
  27660. }
  27661. if (!this.activeCamera) {
  27662. return;
  27663. }
  27664. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27665. this.activeCamera._activeMeshes.reset();
  27666. this._activeMeshes.reset();
  27667. this._renderingManager.reset();
  27668. this._processedMaterials.reset();
  27669. this._activeParticleSystems.reset();
  27670. this._activeSkeletons.reset();
  27671. this._softwareSkinnedMeshes.reset();
  27672. if (this._boundingBoxRenderer) {
  27673. this._boundingBoxRenderer.reset();
  27674. }
  27675. // Meshes
  27676. var meshes;
  27677. var len;
  27678. var checkIsEnabled = true;
  27679. // Determine mesh candidates
  27680. if (this._activeMeshCandidateProvider !== undefined) {
  27681. // Use _activeMeshCandidateProvider
  27682. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27683. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27684. if (meshes !== undefined) {
  27685. len = meshes.length;
  27686. }
  27687. else {
  27688. len = 0;
  27689. }
  27690. }
  27691. else if (this._selectionOctree !== undefined) {
  27692. // Octree
  27693. var selection = this._selectionOctree.select(this._frustumPlanes);
  27694. meshes = selection.data;
  27695. len = selection.length;
  27696. }
  27697. else {
  27698. // Full scene traversal
  27699. len = this.meshes.length;
  27700. meshes = this.meshes;
  27701. }
  27702. // Check each mesh
  27703. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27704. mesh = meshes[meshIndex];
  27705. if (mesh.isBlocked) {
  27706. continue;
  27707. }
  27708. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27709. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27710. continue;
  27711. }
  27712. mesh.computeWorldMatrix();
  27713. // Intersections
  27714. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27715. this._meshesForIntersections.pushNoDuplicate(mesh);
  27716. }
  27717. // Switch to current LOD
  27718. meshLOD = mesh.getLOD(this.activeCamera);
  27719. if (meshLOD === undefined || meshLOD === null) {
  27720. continue;
  27721. }
  27722. mesh._preActivate();
  27723. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27724. this._activeMeshes.push(mesh);
  27725. this.activeCamera._activeMeshes.push(mesh);
  27726. mesh._activate(this._renderId);
  27727. if (meshLOD !== mesh) {
  27728. meshLOD._activate(this._renderId);
  27729. }
  27730. this._activeMesh(mesh, meshLOD);
  27731. }
  27732. }
  27733. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27734. // Particle systems
  27735. if (this.particlesEnabled) {
  27736. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27737. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27738. var particleSystem = this.particleSystems[particleIndex];
  27739. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27740. continue;
  27741. }
  27742. var emitter = particleSystem.emitter;
  27743. if (!emitter.position || emitter.isEnabled()) {
  27744. this._activeParticleSystems.push(particleSystem);
  27745. particleSystem.animate();
  27746. this._renderingManager.dispatchParticles(particleSystem);
  27747. }
  27748. }
  27749. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27750. }
  27751. };
  27752. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27753. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27754. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27755. mesh.skeleton.prepare();
  27756. }
  27757. if (!mesh.computeBonesUsingShaders) {
  27758. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27759. }
  27760. }
  27761. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27762. var boundingInfo = sourceMesh.getBoundingInfo();
  27763. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27764. }
  27765. if (mesh !== undefined && mesh !== null
  27766. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27767. // Submeshes Octrees
  27768. var len;
  27769. var subMeshes;
  27770. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27771. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27772. len = intersections.length;
  27773. subMeshes = intersections.data;
  27774. }
  27775. else {
  27776. subMeshes = mesh.subMeshes;
  27777. len = subMeshes.length;
  27778. }
  27779. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27780. subMesh = subMeshes[subIndex];
  27781. this._evaluateSubMesh(subMesh, mesh);
  27782. }
  27783. }
  27784. };
  27785. /**
  27786. * Update the transform matrix to update from the current active camera
  27787. * @param force defines a boolean used to force the update even if cache is up to date
  27788. */
  27789. Scene.prototype.updateTransformMatrix = function (force) {
  27790. if (!this.activeCamera) {
  27791. return;
  27792. }
  27793. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27794. };
  27795. /**
  27796. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27797. * @param alternateCamera defines the camera to use
  27798. */
  27799. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27800. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27801. };
  27802. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27803. if (camera && camera._skipRendering) {
  27804. return;
  27805. }
  27806. var engine = this._engine;
  27807. this.activeCamera = camera;
  27808. if (!this.activeCamera)
  27809. throw new Error("Active camera not set");
  27810. // Viewport
  27811. engine.setViewport(this.activeCamera.viewport);
  27812. // Camera
  27813. this.resetCachedMaterial();
  27814. this._renderId++;
  27815. this.updateTransformMatrix();
  27816. if (camera._alternateCamera) {
  27817. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27818. this._alternateRendering = true;
  27819. }
  27820. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27821. // Meshes
  27822. this._evaluateActiveMeshes();
  27823. // Software skinning
  27824. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27825. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27826. mesh.applySkeleton(mesh.skeleton);
  27827. }
  27828. // Render targets
  27829. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27830. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27831. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27832. }
  27833. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27834. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27835. }
  27836. if (this.renderTargetsEnabled) {
  27837. this._intermediateRendering = true;
  27838. if (this._renderTargets.length > 0) {
  27839. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27840. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27841. var renderTarget = this._renderTargets.data[renderIndex];
  27842. if (renderTarget._shouldRender()) {
  27843. this._renderId++;
  27844. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27845. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27846. }
  27847. }
  27848. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27849. this._renderId++;
  27850. }
  27851. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27852. var step = _a[_i];
  27853. step.action(this.activeCamera);
  27854. }
  27855. this._intermediateRendering = false;
  27856. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27857. }
  27858. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27859. // Prepare Frame
  27860. if (this.postProcessManager) {
  27861. this.postProcessManager._prepareFrame();
  27862. }
  27863. // Before Camera Draw
  27864. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27865. var step = _c[_b];
  27866. step.action(this.activeCamera);
  27867. }
  27868. // Render
  27869. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27870. this._renderingManager.render(null, null, true, true);
  27871. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27872. // After Camera Draw
  27873. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27874. var step = _e[_d];
  27875. step.action(this.activeCamera);
  27876. }
  27877. // Bounding boxes
  27878. if (this._boundingBoxRenderer) {
  27879. this._boundingBoxRenderer.render();
  27880. }
  27881. // Finalize frame
  27882. if (this.postProcessManager) {
  27883. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27884. }
  27885. // Reset some special arrays
  27886. this._renderTargets.reset();
  27887. this._alternateRendering = false;
  27888. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27889. };
  27890. Scene.prototype._processSubCameras = function (camera) {
  27891. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27892. this._renderForCamera(camera);
  27893. return;
  27894. }
  27895. // rig cameras
  27896. for (var index = 0; index < camera._rigCameras.length; index++) {
  27897. this._renderForCamera(camera._rigCameras[index], camera);
  27898. }
  27899. this.activeCamera = camera;
  27900. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27901. };
  27902. Scene.prototype._checkIntersections = function () {
  27903. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27904. var sourceMesh = this._meshesForIntersections.data[index];
  27905. if (!sourceMesh.actionManager) {
  27906. continue;
  27907. }
  27908. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27909. var action = sourceMesh.actionManager.actions[actionIndex];
  27910. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27911. var parameters = action.getTriggerParameter();
  27912. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27913. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27914. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27915. if (areIntersecting && currentIntersectionInProgress === -1) {
  27916. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27917. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27918. sourceMesh._intersectionsInProgress.push(otherMesh);
  27919. }
  27920. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27921. sourceMesh._intersectionsInProgress.push(otherMesh);
  27922. }
  27923. }
  27924. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27925. //They intersected, and now they don't.
  27926. //is this trigger an exit trigger? execute an event.
  27927. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27928. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27929. }
  27930. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27931. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27932. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27933. return otherMesh === parameterMesh;
  27934. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27935. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27936. }
  27937. }
  27938. }
  27939. }
  27940. }
  27941. };
  27942. /**
  27943. * Render the scene
  27944. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27945. */
  27946. Scene.prototype.render = function (updateCameras) {
  27947. if (updateCameras === void 0) { updateCameras = true; }
  27948. if (this.isDisposed) {
  27949. return;
  27950. }
  27951. // Register components that have been associated lately to the scene.
  27952. this._registerTransientComponents();
  27953. this._activeParticles.fetchNewFrame();
  27954. this._totalVertices.fetchNewFrame();
  27955. this._activeIndices.fetchNewFrame();
  27956. this._activeBones.fetchNewFrame();
  27957. this._meshesForIntersections.reset();
  27958. this.resetCachedMaterial();
  27959. this.onBeforeAnimationsObservable.notifyObservers(this);
  27960. // Actions
  27961. if (this.actionManager) {
  27962. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27963. }
  27964. //Simplification Queue
  27965. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27966. this.simplificationQueue.executeNext();
  27967. }
  27968. if (this._engine.isDeterministicLockStep()) {
  27969. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27970. var defaultFPS = (60.0 / 1000.0);
  27971. var defaultFrameTime = 1000 / 60; // frame time in MS
  27972. if (this._physicsEngine) {
  27973. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27974. }
  27975. var stepsTaken = 0;
  27976. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27977. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27978. internalSteps = Math.min(internalSteps, maxSubSteps);
  27979. do {
  27980. this.onBeforeStepObservable.notifyObservers(this);
  27981. // Animations
  27982. this._animationRatio = defaultFrameTime * defaultFPS;
  27983. this._animate();
  27984. this.onAfterAnimationsObservable.notifyObservers(this);
  27985. // Physics
  27986. if (this._physicsEngine) {
  27987. this.onBeforePhysicsObservable.notifyObservers(this);
  27988. this._physicsEngine._step(defaultFrameTime / 1000);
  27989. this.onAfterPhysicsObservable.notifyObservers(this);
  27990. }
  27991. this.onAfterStepObservable.notifyObservers(this);
  27992. this._currentStepId++;
  27993. stepsTaken++;
  27994. deltaTime -= defaultFrameTime;
  27995. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27996. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27997. }
  27998. else {
  27999. // Animations
  28000. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28001. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28002. this._animate();
  28003. this.onAfterAnimationsObservable.notifyObservers(this);
  28004. // Physics
  28005. if (this._physicsEngine) {
  28006. this.onBeforePhysicsObservable.notifyObservers(this);
  28007. this._physicsEngine._step(deltaTime / 1000.0);
  28008. this.onAfterPhysicsObservable.notifyObservers(this);
  28009. }
  28010. }
  28011. // update gamepad manager
  28012. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  28013. this._gamepadManager._checkGamepadsStatus();
  28014. }
  28015. // Update Cameras
  28016. if (updateCameras) {
  28017. if (this.activeCameras.length > 0) {
  28018. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28019. var camera = this.activeCameras[cameraIndex];
  28020. camera.update();
  28021. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28022. // rig cameras
  28023. for (var index = 0; index < camera._rigCameras.length; index++) {
  28024. camera._rigCameras[index].update();
  28025. }
  28026. }
  28027. }
  28028. }
  28029. else if (this.activeCamera) {
  28030. this.activeCamera.update();
  28031. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28032. // rig cameras
  28033. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28034. this.activeCamera._rigCameras[index].update();
  28035. }
  28036. }
  28037. }
  28038. }
  28039. // Before render
  28040. this.onBeforeRenderObservable.notifyObservers(this);
  28041. // Customs render targets
  28042. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28043. var engine = this.getEngine();
  28044. var currentActiveCamera = this.activeCamera;
  28045. if (this.renderTargetsEnabled) {
  28046. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28047. this._intermediateRendering = true;
  28048. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28049. var renderTarget = this.customRenderTargets[customIndex];
  28050. if (renderTarget._shouldRender()) {
  28051. this._renderId++;
  28052. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28053. if (!this.activeCamera)
  28054. throw new Error("Active camera not set");
  28055. // Viewport
  28056. engine.setViewport(this.activeCamera.viewport);
  28057. // Camera
  28058. this.updateTransformMatrix();
  28059. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28060. }
  28061. }
  28062. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28063. this._intermediateRendering = false;
  28064. this._renderId++;
  28065. }
  28066. // Restore back buffer
  28067. if (this.customRenderTargets.length > 0) {
  28068. engine.restoreDefaultFramebuffer();
  28069. }
  28070. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28071. this.activeCamera = currentActiveCamera;
  28072. // Procedural textures
  28073. if (this.proceduralTexturesEnabled) {
  28074. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28075. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28076. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28077. if (proceduralTexture._shouldRender()) {
  28078. proceduralTexture.render();
  28079. }
  28080. }
  28081. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28082. }
  28083. // Clear
  28084. if (this.autoClearDepthAndStencil || this.autoClear) {
  28085. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28086. }
  28087. // Shadows
  28088. if (this.shadowsEnabled) {
  28089. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28090. var light = this.lights[lightIndex];
  28091. var shadowGenerator = light.getShadowGenerator();
  28092. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28093. var shadowMap = (shadowGenerator.getShadowMap());
  28094. if (this.textures.indexOf(shadowMap) !== -1) {
  28095. this._renderTargets.push(shadowMap);
  28096. }
  28097. }
  28098. }
  28099. }
  28100. // Depth renderer
  28101. for (var key in this._depthRenderer) {
  28102. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28103. }
  28104. // Geometry renderer
  28105. if (this._geometryBufferRenderer) {
  28106. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28107. }
  28108. // RenderPipeline
  28109. if (this._postProcessRenderPipelineManager) {
  28110. this._postProcessRenderPipelineManager.update();
  28111. }
  28112. // Multi-cameras?
  28113. if (this.activeCameras.length > 0) {
  28114. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28115. if (cameraIndex > 0) {
  28116. this._engine.clear(null, false, true, true);
  28117. }
  28118. this._processSubCameras(this.activeCameras[cameraIndex]);
  28119. }
  28120. }
  28121. else {
  28122. if (!this.activeCamera) {
  28123. throw new Error("No camera defined");
  28124. }
  28125. this._processSubCameras(this.activeCamera);
  28126. }
  28127. // Intersection checks
  28128. this._checkIntersections();
  28129. // Update the audio listener attached to the camera
  28130. if (BABYLON.AudioEngine) {
  28131. this._updateAudioParameters();
  28132. }
  28133. // After render
  28134. if (this.afterRender) {
  28135. this.afterRender();
  28136. }
  28137. this.onAfterRenderObservable.notifyObservers(this);
  28138. // Cleaning
  28139. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28140. var data = this._toBeDisposed.data[index];
  28141. if (data) {
  28142. data.dispose();
  28143. }
  28144. this._toBeDisposed[index] = null;
  28145. }
  28146. this._toBeDisposed.reset();
  28147. if (this.dumpNextRenderTargets) {
  28148. this.dumpNextRenderTargets = false;
  28149. }
  28150. this._activeBones.addCount(0, true);
  28151. this._activeIndices.addCount(0, true);
  28152. this._activeParticles.addCount(0, true);
  28153. };
  28154. Scene.prototype._updateAudioParameters = function () {
  28155. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28156. return;
  28157. }
  28158. var listeningCamera;
  28159. var audioEngine = BABYLON.Engine.audioEngine;
  28160. if (this.activeCameras.length > 0) {
  28161. listeningCamera = this.activeCameras[0];
  28162. }
  28163. else {
  28164. listeningCamera = this.activeCamera;
  28165. }
  28166. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28167. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28168. // for VR cameras
  28169. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28170. listeningCamera = listeningCamera.rigCameras[0];
  28171. }
  28172. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28173. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28174. cameraDirection.normalize();
  28175. // To avoid some errors on GearVR
  28176. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28177. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28178. }
  28179. var i;
  28180. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28181. var sound = this.mainSoundTrack.soundCollection[i];
  28182. if (sound.useCustomAttenuation) {
  28183. sound.updateDistanceFromListener();
  28184. }
  28185. }
  28186. for (i = 0; i < this.soundTracks.length; i++) {
  28187. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28188. sound = this.soundTracks[i].soundCollection[j];
  28189. if (sound.useCustomAttenuation) {
  28190. sound.updateDistanceFromListener();
  28191. }
  28192. }
  28193. }
  28194. }
  28195. };
  28196. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28197. // Audio
  28198. /**
  28199. * Gets or sets if audio support is enabled
  28200. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28201. */
  28202. get: function () {
  28203. return this._audioEnabled;
  28204. },
  28205. set: function (value) {
  28206. this._audioEnabled = value;
  28207. if (BABYLON.AudioEngine) {
  28208. if (this._audioEnabled) {
  28209. this._enableAudio();
  28210. }
  28211. else {
  28212. this._disableAudio();
  28213. }
  28214. }
  28215. },
  28216. enumerable: true,
  28217. configurable: true
  28218. });
  28219. Scene.prototype._disableAudio = function () {
  28220. var i;
  28221. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28222. this.mainSoundTrack.soundCollection[i].pause();
  28223. }
  28224. for (i = 0; i < this.soundTracks.length; i++) {
  28225. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28226. this.soundTracks[i].soundCollection[j].pause();
  28227. }
  28228. }
  28229. };
  28230. Scene.prototype._enableAudio = function () {
  28231. var i;
  28232. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28233. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28234. this.mainSoundTrack.soundCollection[i].play();
  28235. }
  28236. }
  28237. for (i = 0; i < this.soundTracks.length; i++) {
  28238. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28239. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28240. this.soundTracks[i].soundCollection[j].play();
  28241. }
  28242. }
  28243. }
  28244. };
  28245. Object.defineProperty(Scene.prototype, "headphone", {
  28246. /**
  28247. * Gets or sets if audio will be output to headphones
  28248. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28249. */
  28250. get: function () {
  28251. return this._headphone;
  28252. },
  28253. set: function (value) {
  28254. this._headphone = value;
  28255. if (BABYLON.AudioEngine) {
  28256. if (this._headphone) {
  28257. this._switchAudioModeForHeadphones();
  28258. }
  28259. else {
  28260. this._switchAudioModeForNormalSpeakers();
  28261. }
  28262. }
  28263. },
  28264. enumerable: true,
  28265. configurable: true
  28266. });
  28267. Scene.prototype._switchAudioModeForHeadphones = function () {
  28268. this.mainSoundTrack.switchPanningModelToHRTF();
  28269. for (var i = 0; i < this.soundTracks.length; i++) {
  28270. this.soundTracks[i].switchPanningModelToHRTF();
  28271. }
  28272. };
  28273. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28274. this.mainSoundTrack.switchPanningModelToEqualPower();
  28275. for (var i = 0; i < this.soundTracks.length; i++) {
  28276. this.soundTracks[i].switchPanningModelToEqualPower();
  28277. }
  28278. };
  28279. /**
  28280. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28281. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28282. * @returns the created depth renderer
  28283. */
  28284. Scene.prototype.enableDepthRenderer = function (camera) {
  28285. camera = camera || this.activeCamera;
  28286. if (!camera) {
  28287. throw "No camera available to enable depth renderer";
  28288. }
  28289. if (!this._depthRenderer[camera.id]) {
  28290. var textureType = 0;
  28291. if (this._engine.getCaps().textureHalfFloatRender) {
  28292. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28293. }
  28294. else if (this._engine.getCaps().textureFloatRender) {
  28295. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28296. }
  28297. else {
  28298. throw "Depth renderer does not support int texture type";
  28299. }
  28300. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28301. }
  28302. return this._depthRenderer[camera.id];
  28303. };
  28304. /**
  28305. * Disables a depth renderer for a given camera
  28306. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28307. */
  28308. Scene.prototype.disableDepthRenderer = function (camera) {
  28309. camera = camera || this.activeCamera;
  28310. if (!camera || !this._depthRenderer[camera.id]) {
  28311. return;
  28312. }
  28313. this._depthRenderer[camera.id].dispose();
  28314. delete this._depthRenderer[camera.id];
  28315. };
  28316. /**
  28317. * Enables a GeometryBufferRender and associates it with the scene
  28318. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28319. * @returns the GeometryBufferRenderer
  28320. */
  28321. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28322. if (ratio === void 0) { ratio = 1; }
  28323. if (this._geometryBufferRenderer) {
  28324. return this._geometryBufferRenderer;
  28325. }
  28326. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28327. if (!this._geometryBufferRenderer.isSupported) {
  28328. this._geometryBufferRenderer = null;
  28329. }
  28330. return this._geometryBufferRenderer;
  28331. };
  28332. /**
  28333. * Disables the GeometryBufferRender associated with the scene
  28334. */
  28335. Scene.prototype.disableGeometryBufferRenderer = function () {
  28336. if (!this._geometryBufferRenderer) {
  28337. return;
  28338. }
  28339. this._geometryBufferRenderer.dispose();
  28340. this._geometryBufferRenderer = null;
  28341. };
  28342. /**
  28343. * Freeze all materials
  28344. * A frozen material will not be updatable but should be faster to render
  28345. */
  28346. Scene.prototype.freezeMaterials = function () {
  28347. for (var i = 0; i < this.materials.length; i++) {
  28348. this.materials[i].freeze();
  28349. }
  28350. };
  28351. /**
  28352. * Unfreeze all materials
  28353. * A frozen material will not be updatable but should be faster to render
  28354. */
  28355. Scene.prototype.unfreezeMaterials = function () {
  28356. for (var i = 0; i < this.materials.length; i++) {
  28357. this.materials[i].unfreeze();
  28358. }
  28359. };
  28360. /**
  28361. * Releases all held ressources
  28362. */
  28363. Scene.prototype.dispose = function () {
  28364. this.beforeRender = null;
  28365. this.afterRender = null;
  28366. this.skeletons = [];
  28367. this.morphTargetManagers = [];
  28368. this._transientComponents = [];
  28369. this._isReadyForMeshStage.clear();
  28370. this._cameraDrawRenderTargetStage.clear();
  28371. this._beforeCameraDrawStage.clear();
  28372. this._afterCameraDrawStage.clear();
  28373. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28374. var component = _a[_i];
  28375. component.dispose();
  28376. }
  28377. this.importedMeshesFiles = new Array();
  28378. this.stopAllAnimations();
  28379. this.resetCachedMaterial();
  28380. for (var key in this._depthRenderer) {
  28381. this._depthRenderer[key].dispose();
  28382. }
  28383. if (this._gamepadManager) {
  28384. this._gamepadManager.dispose();
  28385. this._gamepadManager = null;
  28386. }
  28387. // Smart arrays
  28388. if (this.activeCamera) {
  28389. this.activeCamera._activeMeshes.dispose();
  28390. this.activeCamera = null;
  28391. }
  28392. this._activeMeshes.dispose();
  28393. this._renderingManager.dispose();
  28394. this._processedMaterials.dispose();
  28395. this._activeParticleSystems.dispose();
  28396. this._activeSkeletons.dispose();
  28397. this._softwareSkinnedMeshes.dispose();
  28398. this._renderTargets.dispose();
  28399. this._registeredForLateAnimationBindings.dispose();
  28400. if (this._boundingBoxRenderer) {
  28401. this._boundingBoxRenderer.dispose();
  28402. }
  28403. this._meshesForIntersections.dispose();
  28404. this._toBeDisposed.dispose();
  28405. // Abort active requests
  28406. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28407. var request = _c[_b];
  28408. request.abort();
  28409. }
  28410. // Debug layer
  28411. if (this._debugLayer) {
  28412. this._debugLayer.hide();
  28413. }
  28414. // Events
  28415. this.onDisposeObservable.notifyObservers(this);
  28416. this.onDisposeObservable.clear();
  28417. this.onBeforeRenderObservable.clear();
  28418. this.onAfterRenderObservable.clear();
  28419. this.onBeforeRenderTargetsRenderObservable.clear();
  28420. this.onAfterRenderTargetsRenderObservable.clear();
  28421. this.onAfterStepObservable.clear();
  28422. this.onBeforeStepObservable.clear();
  28423. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28424. this.onAfterActiveMeshesEvaluationObservable.clear();
  28425. this.onBeforeParticlesRenderingObservable.clear();
  28426. this.onAfterParticlesRenderingObservable.clear();
  28427. this.onBeforeSpritesRenderingObservable.clear();
  28428. this.onAfterSpritesRenderingObservable.clear();
  28429. this.onBeforeDrawPhaseObservable.clear();
  28430. this.onAfterDrawPhaseObservable.clear();
  28431. this.onBeforePhysicsObservable.clear();
  28432. this.onAfterPhysicsObservable.clear();
  28433. this.onBeforeAnimationsObservable.clear();
  28434. this.onAfterAnimationsObservable.clear();
  28435. this.onDataLoadedObservable.clear();
  28436. this.detachControl();
  28437. // Release sounds & sounds tracks
  28438. if (BABYLON.AudioEngine) {
  28439. this.disposeSounds();
  28440. }
  28441. // VR Helper
  28442. if (this.VRHelper) {
  28443. this.VRHelper.dispose();
  28444. }
  28445. // Detach cameras
  28446. var canvas = this._engine.getRenderingCanvas();
  28447. if (canvas) {
  28448. var index;
  28449. for (index = 0; index < this.cameras.length; index++) {
  28450. this.cameras[index].detachControl(canvas);
  28451. }
  28452. }
  28453. // Release animation groups
  28454. while (this.animationGroups.length) {
  28455. this.animationGroups[0].dispose();
  28456. }
  28457. // Release lights
  28458. while (this.lights.length) {
  28459. this.lights[0].dispose();
  28460. }
  28461. // Release meshes
  28462. while (this.meshes.length) {
  28463. this.meshes[0].dispose(true);
  28464. }
  28465. while (this.transformNodes.length) {
  28466. this.removeTransformNode(this.transformNodes[0]);
  28467. }
  28468. // Release cameras
  28469. while (this.cameras.length) {
  28470. this.cameras[0].dispose();
  28471. }
  28472. // Release materials
  28473. if (this.defaultMaterial) {
  28474. this.defaultMaterial.dispose();
  28475. }
  28476. while (this.multiMaterials.length) {
  28477. this.multiMaterials[0].dispose();
  28478. }
  28479. while (this.materials.length) {
  28480. this.materials[0].dispose();
  28481. }
  28482. // Release particles
  28483. while (this.particleSystems.length) {
  28484. this.particleSystems[0].dispose();
  28485. }
  28486. // Release sprites
  28487. while (this.spriteManagers.length) {
  28488. this.spriteManagers[0].dispose();
  28489. }
  28490. // Release postProcesses
  28491. while (this.postProcesses.length) {
  28492. this.postProcesses[0].dispose();
  28493. }
  28494. // Release textures
  28495. while (this.textures.length) {
  28496. this.textures[0].dispose();
  28497. }
  28498. // Release UBO
  28499. this._sceneUbo.dispose();
  28500. if (this._alternateSceneUbo) {
  28501. this._alternateSceneUbo.dispose();
  28502. }
  28503. // Post-processes
  28504. this.postProcessManager.dispose();
  28505. if (this._postProcessRenderPipelineManager) {
  28506. this._postProcessRenderPipelineManager.dispose();
  28507. }
  28508. // Physics
  28509. if (this._physicsEngine) {
  28510. this.disablePhysicsEngine();
  28511. }
  28512. // Remove from engine
  28513. index = this._engine.scenes.indexOf(this);
  28514. if (index > -1) {
  28515. this._engine.scenes.splice(index, 1);
  28516. }
  28517. this._engine.wipeCaches(true);
  28518. this._isDisposed = true;
  28519. };
  28520. Object.defineProperty(Scene.prototype, "isDisposed", {
  28521. /**
  28522. * Gets if the scene is already disposed
  28523. */
  28524. get: function () {
  28525. return this._isDisposed;
  28526. },
  28527. enumerable: true,
  28528. configurable: true
  28529. });
  28530. /**
  28531. * Releases sounds & soundtracks
  28532. */
  28533. Scene.prototype.disposeSounds = function () {
  28534. if (!this._mainSoundTrack) {
  28535. return;
  28536. }
  28537. this.mainSoundTrack.dispose();
  28538. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28539. this.soundTracks[scIndex].dispose();
  28540. }
  28541. };
  28542. /**
  28543. * Call this function to reduce memory footprint of the scene.
  28544. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28545. */
  28546. Scene.prototype.clearCachedVertexData = function () {
  28547. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28548. var mesh = this.meshes[meshIndex];
  28549. var geometry = mesh.geometry;
  28550. if (geometry) {
  28551. geometry._indices = [];
  28552. for (var vbName in geometry._vertexBuffers) {
  28553. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28554. continue;
  28555. }
  28556. geometry._vertexBuffers[vbName]._buffer._data = null;
  28557. }
  28558. }
  28559. }
  28560. };
  28561. /**
  28562. * This function will remove the local cached buffer data from texture.
  28563. * It will save memory but will prevent the texture from being rebuilt
  28564. */
  28565. Scene.prototype.cleanCachedTextureBuffer = function () {
  28566. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28567. var baseTexture = _a[_i];
  28568. var buffer = baseTexture._buffer;
  28569. if (buffer) {
  28570. baseTexture._buffer = null;
  28571. }
  28572. }
  28573. };
  28574. // Octrees
  28575. /**
  28576. * Get the world extend vectors with an optional filter
  28577. *
  28578. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28579. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28580. */
  28581. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28582. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28583. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28584. filterPredicate = filterPredicate || (function () { return true; });
  28585. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28586. mesh.computeWorldMatrix(true);
  28587. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28588. return;
  28589. }
  28590. var boundingInfo = mesh.getBoundingInfo();
  28591. var minBox = boundingInfo.boundingBox.minimumWorld;
  28592. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28593. BABYLON.Tools.CheckExtends(minBox, min, max);
  28594. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28595. });
  28596. return {
  28597. min: min,
  28598. max: max
  28599. };
  28600. };
  28601. /**
  28602. * Creates or updates the octree used to boost selection (picking)
  28603. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28604. * @param maxCapacity defines the maximum capacity per leaf
  28605. * @param maxDepth defines the maximum depth of the octree
  28606. * @returns an octree of AbstractMesh
  28607. */
  28608. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28609. if (maxCapacity === void 0) { maxCapacity = 64; }
  28610. if (maxDepth === void 0) { maxDepth = 2; }
  28611. if (!this._selectionOctree) {
  28612. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28613. }
  28614. var worldExtends = this.getWorldExtends();
  28615. // Update octree
  28616. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28617. return this._selectionOctree;
  28618. };
  28619. // Picking
  28620. /**
  28621. * Creates a ray that can be used to pick in the scene
  28622. * @param x defines the x coordinate of the origin (on-screen)
  28623. * @param y defines the y coordinate of the origin (on-screen)
  28624. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28625. * @param camera defines the camera to use for the picking
  28626. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28627. * @returns a Ray
  28628. */
  28629. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28630. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28631. var result = BABYLON.Ray.Zero();
  28632. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28633. return result;
  28634. };
  28635. /**
  28636. * Creates a ray that can be used to pick in the scene
  28637. * @param x defines the x coordinate of the origin (on-screen)
  28638. * @param y defines the y coordinate of the origin (on-screen)
  28639. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28640. * @param result defines the ray where to store the picking ray
  28641. * @param camera defines the camera to use for the picking
  28642. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28643. * @returns the current scene
  28644. */
  28645. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28646. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28647. var engine = this._engine;
  28648. if (!camera) {
  28649. if (!this.activeCamera)
  28650. throw new Error("Active camera not set");
  28651. camera = this.activeCamera;
  28652. }
  28653. var cameraViewport = camera.viewport;
  28654. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28655. // Moving coordinates to local viewport world
  28656. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28657. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28658. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28659. return this;
  28660. };
  28661. /**
  28662. * Creates a ray that can be used to pick in the scene
  28663. * @param x defines the x coordinate of the origin (on-screen)
  28664. * @param y defines the y coordinate of the origin (on-screen)
  28665. * @param camera defines the camera to use for the picking
  28666. * @returns a Ray
  28667. */
  28668. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28669. var result = BABYLON.Ray.Zero();
  28670. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28671. return result;
  28672. };
  28673. /**
  28674. * Creates a ray that can be used to pick in the scene
  28675. * @param x defines the x coordinate of the origin (on-screen)
  28676. * @param y defines the y coordinate of the origin (on-screen)
  28677. * @param result defines the ray where to store the picking ray
  28678. * @param camera defines the camera to use for the picking
  28679. * @returns the current scene
  28680. */
  28681. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28682. if (!BABYLON.PickingInfo) {
  28683. return this;
  28684. }
  28685. var engine = this._engine;
  28686. if (!camera) {
  28687. if (!this.activeCamera)
  28688. throw new Error("Active camera not set");
  28689. camera = this.activeCamera;
  28690. }
  28691. var cameraViewport = camera.viewport;
  28692. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28693. var identity = BABYLON.Matrix.Identity();
  28694. // Moving coordinates to local viewport world
  28695. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28696. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28697. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28698. return this;
  28699. };
  28700. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28701. if (!BABYLON.PickingInfo) {
  28702. return null;
  28703. }
  28704. var pickingInfo = null;
  28705. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28706. var mesh = this.meshes[meshIndex];
  28707. if (predicate) {
  28708. if (!predicate(mesh)) {
  28709. continue;
  28710. }
  28711. }
  28712. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28713. continue;
  28714. }
  28715. var world = mesh.getWorldMatrix();
  28716. var ray = rayFunction(world);
  28717. var result = mesh.intersects(ray, fastCheck);
  28718. if (!result || !result.hit)
  28719. continue;
  28720. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28721. continue;
  28722. pickingInfo = result;
  28723. if (fastCheck) {
  28724. break;
  28725. }
  28726. }
  28727. return pickingInfo || new BABYLON.PickingInfo();
  28728. };
  28729. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28730. if (!BABYLON.PickingInfo) {
  28731. return null;
  28732. }
  28733. var pickingInfos = new Array();
  28734. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28735. var mesh = this.meshes[meshIndex];
  28736. if (predicate) {
  28737. if (!predicate(mesh)) {
  28738. continue;
  28739. }
  28740. }
  28741. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28742. continue;
  28743. }
  28744. var world = mesh.getWorldMatrix();
  28745. var ray = rayFunction(world);
  28746. var result = mesh.intersects(ray, false);
  28747. if (!result || !result.hit)
  28748. continue;
  28749. pickingInfos.push(result);
  28750. }
  28751. return pickingInfos;
  28752. };
  28753. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28754. if (!BABYLON.PickingInfo) {
  28755. return null;
  28756. }
  28757. var pickingInfo = null;
  28758. if (!camera) {
  28759. if (!this.activeCamera) {
  28760. return null;
  28761. }
  28762. camera = this.activeCamera;
  28763. }
  28764. if (this.spriteManagers.length > 0) {
  28765. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28766. var spriteManager = this.spriteManagers[spriteIndex];
  28767. if (!spriteManager.isPickable) {
  28768. continue;
  28769. }
  28770. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28771. if (!result || !result.hit)
  28772. continue;
  28773. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28774. continue;
  28775. pickingInfo = result;
  28776. if (fastCheck) {
  28777. break;
  28778. }
  28779. }
  28780. }
  28781. return pickingInfo || new BABYLON.PickingInfo();
  28782. };
  28783. /** Launch a ray to try to pick a mesh in the scene
  28784. * @param x position on screen
  28785. * @param y position on screen
  28786. * @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
  28787. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28788. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28789. * @returns a PickingInfo
  28790. */
  28791. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28792. var _this = this;
  28793. if (!BABYLON.PickingInfo) {
  28794. return null;
  28795. }
  28796. var result = this._internalPick(function (world) {
  28797. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28798. return _this._tempPickingRay;
  28799. }, predicate, fastCheck);
  28800. if (result) {
  28801. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28802. }
  28803. return result;
  28804. };
  28805. /** Launch a ray to try to pick a sprite in the scene
  28806. * @param x position on screen
  28807. * @param y position on screen
  28808. * @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
  28809. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28810. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28811. * @returns a PickingInfo
  28812. */
  28813. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28814. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28815. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28816. };
  28817. /** Use the given ray to pick a mesh in the scene
  28818. * @param ray The ray to use to pick meshes
  28819. * @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
  28820. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28821. * @returns a PickingInfo
  28822. */
  28823. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28824. var _this = this;
  28825. var result = this._internalPick(function (world) {
  28826. if (!_this._pickWithRayInverseMatrix) {
  28827. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28828. }
  28829. world.invertToRef(_this._pickWithRayInverseMatrix);
  28830. if (!_this._cachedRayForTransform) {
  28831. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28832. }
  28833. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28834. return _this._cachedRayForTransform;
  28835. }, predicate, fastCheck);
  28836. if (result) {
  28837. result.ray = ray;
  28838. }
  28839. return result;
  28840. };
  28841. /**
  28842. * Launch a ray to try to pick a mesh in the scene
  28843. * @param x X position on screen
  28844. * @param y Y position on screen
  28845. * @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
  28846. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28847. * @returns an array of PickingInfo
  28848. */
  28849. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28850. var _this = this;
  28851. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28852. };
  28853. /**
  28854. * Launch a ray to try to pick a mesh in the scene
  28855. * @param ray Ray to use
  28856. * @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
  28857. * @returns an array of PickingInfo
  28858. */
  28859. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28860. var _this = this;
  28861. return this._internalMultiPick(function (world) {
  28862. if (!_this._pickWithRayInverseMatrix) {
  28863. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28864. }
  28865. world.invertToRef(_this._pickWithRayInverseMatrix);
  28866. if (!_this._cachedRayForTransform) {
  28867. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28868. }
  28869. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28870. return _this._cachedRayForTransform;
  28871. }, predicate);
  28872. };
  28873. /**
  28874. * Force the value of meshUnderPointer
  28875. * @param mesh defines the mesh to use
  28876. */
  28877. Scene.prototype.setPointerOverMesh = function (mesh) {
  28878. if (this._pointerOverMesh === mesh) {
  28879. return;
  28880. }
  28881. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28882. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28883. }
  28884. this._pointerOverMesh = mesh;
  28885. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28886. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28887. }
  28888. };
  28889. /**
  28890. * Gets the mesh under the pointer
  28891. * @returns a Mesh or null if no mesh is under the pointer
  28892. */
  28893. Scene.prototype.getPointerOverMesh = function () {
  28894. return this._pointerOverMesh;
  28895. };
  28896. /**
  28897. * Force the sprite under the pointer
  28898. * @param sprite defines the sprite to use
  28899. */
  28900. Scene.prototype.setPointerOverSprite = function (sprite) {
  28901. if (this._pointerOverSprite === sprite) {
  28902. return;
  28903. }
  28904. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28905. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28906. }
  28907. this._pointerOverSprite = sprite;
  28908. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28909. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28910. }
  28911. };
  28912. /**
  28913. * Gets the sprite under the pointer
  28914. * @returns a Sprite or null if no sprite is under the pointer
  28915. */
  28916. Scene.prototype.getPointerOverSprite = function () {
  28917. return this._pointerOverSprite;
  28918. };
  28919. // Physics
  28920. /**
  28921. * Gets the current physics engine
  28922. * @returns a PhysicsEngine or null if none attached
  28923. */
  28924. Scene.prototype.getPhysicsEngine = function () {
  28925. return this._physicsEngine;
  28926. };
  28927. /**
  28928. * Enables physics to the current scene
  28929. * @param gravity defines the scene's gravity for the physics engine
  28930. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28931. * @return a boolean indicating if the physics engine was initialized
  28932. */
  28933. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28934. if (gravity === void 0) { gravity = null; }
  28935. if (this._physicsEngine) {
  28936. return true;
  28937. }
  28938. try {
  28939. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28940. return true;
  28941. }
  28942. catch (e) {
  28943. BABYLON.Tools.Error(e.message);
  28944. return false;
  28945. }
  28946. };
  28947. /**
  28948. * Disables and disposes the physics engine associated with the scene
  28949. */
  28950. Scene.prototype.disablePhysicsEngine = function () {
  28951. if (!this._physicsEngine) {
  28952. return;
  28953. }
  28954. this._physicsEngine.dispose();
  28955. this._physicsEngine = null;
  28956. };
  28957. /**
  28958. * Gets a boolean indicating if there is an active physics engine
  28959. * @returns a boolean indicating if there is an active physics engine
  28960. */
  28961. Scene.prototype.isPhysicsEnabled = function () {
  28962. return this._physicsEngine !== undefined;
  28963. };
  28964. /**
  28965. * Deletes a physics compound impostor
  28966. * @param compound defines the compound to delete
  28967. */
  28968. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28969. var mesh = compound.parts[0].mesh;
  28970. if (mesh.physicsImpostor) {
  28971. mesh.physicsImpostor.dispose( /*true*/);
  28972. mesh.physicsImpostor = null;
  28973. }
  28974. };
  28975. // Misc.
  28976. /** @hidden */
  28977. Scene.prototype._rebuildGeometries = function () {
  28978. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28979. var geometry = _a[_i];
  28980. geometry._rebuild();
  28981. }
  28982. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28983. var mesh = _c[_b];
  28984. mesh._rebuild();
  28985. }
  28986. if (this.postProcessManager) {
  28987. this.postProcessManager._rebuild();
  28988. }
  28989. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28990. var component = _e[_d];
  28991. component.rebuild();
  28992. }
  28993. if (this._boundingBoxRenderer) {
  28994. this._boundingBoxRenderer._rebuild();
  28995. }
  28996. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28997. var system = _g[_f];
  28998. system.rebuild();
  28999. }
  29000. if (this._postProcessRenderPipelineManager) {
  29001. this._postProcessRenderPipelineManager._rebuild();
  29002. }
  29003. };
  29004. /** @hidden */
  29005. Scene.prototype._rebuildTextures = function () {
  29006. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29007. var texture = _a[_i];
  29008. texture._rebuild();
  29009. }
  29010. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29011. };
  29012. /**
  29013. * Creates a default light for the scene.
  29014. * @param replace Whether to replace the existing lights in the scene.
  29015. */
  29016. Scene.prototype.createDefaultLight = function (replace) {
  29017. if (replace === void 0) { replace = false; }
  29018. // Dispose existing light in replace mode.
  29019. if (replace) {
  29020. if (this.lights) {
  29021. for (var i = 0; i < this.lights.length; i++) {
  29022. this.lights[i].dispose();
  29023. }
  29024. }
  29025. }
  29026. // Light
  29027. if (this.lights.length === 0) {
  29028. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  29029. }
  29030. };
  29031. /**
  29032. * Creates a default camera for the scene.
  29033. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  29034. * @param replace Whether to replace the existing active camera in the scene.
  29035. * @param attachCameraControls Whether to attach camera controls to the canvas.
  29036. */
  29037. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  29038. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29039. if (replace === void 0) { replace = false; }
  29040. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29041. // Dispose existing camera in replace mode.
  29042. if (replace) {
  29043. if (this.activeCamera) {
  29044. this.activeCamera.dispose();
  29045. this.activeCamera = null;
  29046. }
  29047. }
  29048. // Camera
  29049. if (!this.activeCamera) {
  29050. var worldExtends = this.getWorldExtends();
  29051. var worldSize = worldExtends.max.subtract(worldExtends.min);
  29052. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  29053. var camera;
  29054. var radius = worldSize.length() * 1.5;
  29055. // empty scene scenario!
  29056. if (!isFinite(radius)) {
  29057. radius = 1;
  29058. worldCenter.copyFromFloats(0, 0, 0);
  29059. }
  29060. if (createArcRotateCamera) {
  29061. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  29062. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  29063. arcRotateCamera.wheelPrecision = 100 / radius;
  29064. camera = arcRotateCamera;
  29065. }
  29066. else {
  29067. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  29068. freeCamera.setTarget(worldCenter);
  29069. camera = freeCamera;
  29070. }
  29071. camera.minZ = radius * 0.01;
  29072. camera.maxZ = radius * 1000;
  29073. camera.speed = radius * 0.2;
  29074. this.activeCamera = camera;
  29075. var canvas = this.getEngine().getRenderingCanvas();
  29076. if (attachCameraControls && canvas) {
  29077. camera.attachControl(canvas);
  29078. }
  29079. }
  29080. };
  29081. /**
  29082. * Creates a default camera and a default light
  29083. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29084. * @param replace defines if the camera and/or light will replace the existing ones
  29085. * @param attachCameraControls defines if attachControl will be called on the new camera
  29086. */
  29087. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29088. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29089. if (replace === void 0) { replace = false; }
  29090. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29091. this.createDefaultLight(replace);
  29092. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29093. };
  29094. /**
  29095. * Creates a new sky box
  29096. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29097. * @param environmentTexture defines the texture to use as environment texture
  29098. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29099. * @param scale defines the overall scale of the skybox
  29100. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29101. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29102. * @returns a new mesh holding the sky box
  29103. */
  29104. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29105. if (pbr === void 0) { pbr = false; }
  29106. if (scale === void 0) { scale = 1000; }
  29107. if (blur === void 0) { blur = 0; }
  29108. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29109. if (!environmentTexture) {
  29110. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29111. return null;
  29112. }
  29113. if (setGlobalEnvTexture) {
  29114. if (environmentTexture) {
  29115. this.environmentTexture = environmentTexture;
  29116. }
  29117. }
  29118. // Skybox
  29119. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29120. if (pbr) {
  29121. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29122. hdrSkyboxMaterial.backFaceCulling = false;
  29123. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29124. if (hdrSkyboxMaterial.reflectionTexture) {
  29125. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29126. }
  29127. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29128. hdrSkyboxMaterial.disableLighting = true;
  29129. hdrSkyboxMaterial.twoSidedLighting = true;
  29130. hdrSkybox.infiniteDistance = true;
  29131. hdrSkybox.material = hdrSkyboxMaterial;
  29132. }
  29133. else {
  29134. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29135. skyboxMaterial.backFaceCulling = false;
  29136. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29137. if (skyboxMaterial.reflectionTexture) {
  29138. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29139. }
  29140. skyboxMaterial.disableLighting = true;
  29141. hdrSkybox.infiniteDistance = true;
  29142. hdrSkybox.material = skyboxMaterial;
  29143. }
  29144. return hdrSkybox;
  29145. };
  29146. /**
  29147. * Creates a new environment
  29148. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29149. * @param options defines the options you can use to configure the environment
  29150. * @returns the new EnvironmentHelper
  29151. */
  29152. Scene.prototype.createDefaultEnvironment = function (options) {
  29153. if (BABYLON.EnvironmentHelper) {
  29154. return new BABYLON.EnvironmentHelper(options, this);
  29155. }
  29156. return null;
  29157. };
  29158. /**
  29159. * Creates a new VREXperienceHelper
  29160. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29161. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29162. * @returns a new VREXperienceHelper
  29163. */
  29164. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29165. if (webVROptions === void 0) { webVROptions = {}; }
  29166. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29167. };
  29168. // Tags
  29169. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29170. if (tagsQuery === undefined) {
  29171. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29172. return list;
  29173. }
  29174. var listByTags = [];
  29175. forEach = forEach || (function (item) { return; });
  29176. for (var i in list) {
  29177. var item = list[i];
  29178. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29179. listByTags.push(item);
  29180. forEach(item);
  29181. }
  29182. }
  29183. return listByTags;
  29184. };
  29185. /**
  29186. * Get a list of meshes by tags
  29187. * @param tagsQuery defines the tags query to use
  29188. * @param forEach defines a predicate used to filter results
  29189. * @returns an array of Mesh
  29190. */
  29191. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29192. return this._getByTags(this.meshes, tagsQuery, forEach);
  29193. };
  29194. /**
  29195. * Get a list of cameras by tags
  29196. * @param tagsQuery defines the tags query to use
  29197. * @param forEach defines a predicate used to filter results
  29198. * @returns an array of Camera
  29199. */
  29200. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29201. return this._getByTags(this.cameras, tagsQuery, forEach);
  29202. };
  29203. /**
  29204. * Get a list of lights by tags
  29205. * @param tagsQuery defines the tags query to use
  29206. * @param forEach defines a predicate used to filter results
  29207. * @returns an array of Light
  29208. */
  29209. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29210. return this._getByTags(this.lights, tagsQuery, forEach);
  29211. };
  29212. /**
  29213. * Get a list of materials by tags
  29214. * @param tagsQuery defines the tags query to use
  29215. * @param forEach defines a predicate used to filter results
  29216. * @returns an array of Material
  29217. */
  29218. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29219. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29220. };
  29221. /**
  29222. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29223. * This allowed control for front to back rendering or reversly depending of the special needs.
  29224. *
  29225. * @param renderingGroupId The rendering group id corresponding to its index
  29226. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29227. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29228. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29229. */
  29230. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29231. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29232. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29233. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29234. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29235. };
  29236. /**
  29237. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29238. *
  29239. * @param renderingGroupId The rendering group id corresponding to its index
  29240. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29241. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29242. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29243. */
  29244. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29245. if (depth === void 0) { depth = true; }
  29246. if (stencil === void 0) { stencil = true; }
  29247. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29248. };
  29249. /**
  29250. * Will flag all materials as dirty to trigger new shader compilation
  29251. * @param flag defines the flag used to specify which material part must be marked as dirty
  29252. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29253. */
  29254. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29255. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29256. var material = _a[_i];
  29257. if (predicate && !predicate(material)) {
  29258. continue;
  29259. }
  29260. material.markAsDirty(flag);
  29261. }
  29262. };
  29263. /** @hidden */
  29264. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29265. var _this = this;
  29266. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29267. this._activeRequests.push(request);
  29268. request.onCompleteObservable.add(function (request) {
  29269. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29270. });
  29271. return request;
  29272. };
  29273. /** @hidden */
  29274. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29275. var _this = this;
  29276. return new Promise(function (resolve, reject) {
  29277. _this._loadFile(url, function (data) {
  29278. resolve(data);
  29279. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29280. reject(exception);
  29281. });
  29282. });
  29283. };
  29284. // Statics
  29285. Scene._FOGMODE_NONE = 0;
  29286. Scene._FOGMODE_EXP = 1;
  29287. Scene._FOGMODE_EXP2 = 2;
  29288. Scene._FOGMODE_LINEAR = 3;
  29289. Scene._uniqueIdCounter = 0;
  29290. /**
  29291. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29292. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29293. */
  29294. Scene.MinDeltaTime = 1.0;
  29295. /**
  29296. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29297. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29298. */
  29299. Scene.MaxDeltaTime = 1000.0;
  29300. /** The distance in pixel that you have to move to prevent some events */
  29301. Scene.DragMovementThreshold = 10; // in pixels
  29302. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29303. Scene.LongPressDelay = 500; // in milliseconds
  29304. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29305. Scene.DoubleClickDelay = 300; // in milliseconds
  29306. /** If you need to check double click without raising a single click at first click, enable this flag */
  29307. Scene.ExclusiveDoubleClickMode = false;
  29308. return Scene;
  29309. }(BABYLON.AbstractScene));
  29310. BABYLON.Scene = Scene;
  29311. })(BABYLON || (BABYLON = {}));
  29312. //# sourceMappingURL=babylon.scene.js.map
  29313. var BABYLON;
  29314. (function (BABYLON) {
  29315. /**
  29316. * Set of assets to keep when moving a scene into an asset container.
  29317. */
  29318. var KeepAssets = /** @class */ (function (_super) {
  29319. __extends(KeepAssets, _super);
  29320. function KeepAssets() {
  29321. return _super !== null && _super.apply(this, arguments) || this;
  29322. }
  29323. return KeepAssets;
  29324. }(BABYLON.AbstractScene));
  29325. BABYLON.KeepAssets = KeepAssets;
  29326. /**
  29327. * Container with a set of assets that can be added or removed from a scene.
  29328. */
  29329. var AssetContainer = /** @class */ (function (_super) {
  29330. __extends(AssetContainer, _super);
  29331. /**
  29332. * Instantiates an AssetContainer.
  29333. * @param scene The scene the AssetContainer belongs to.
  29334. */
  29335. function AssetContainer(scene) {
  29336. var _this = _super.call(this) || this;
  29337. _this.scene = scene;
  29338. return _this;
  29339. }
  29340. /**
  29341. * Adds all the assets from the container to the scene.
  29342. */
  29343. AssetContainer.prototype.addAllToScene = function () {
  29344. var _this = this;
  29345. this.cameras.forEach(function (o) {
  29346. _this.scene.addCamera(o);
  29347. });
  29348. this.lights.forEach(function (o) {
  29349. _this.scene.addLight(o);
  29350. });
  29351. this.meshes.forEach(function (o) {
  29352. _this.scene.addMesh(o);
  29353. });
  29354. this.skeletons.forEach(function (o) {
  29355. _this.scene.addSkeleton(o);
  29356. });
  29357. this.particleSystems.forEach(function (o) {
  29358. _this.scene.addParticleSystem(o);
  29359. });
  29360. this.animations.forEach(function (o) {
  29361. _this.scene.addAnimation(o);
  29362. });
  29363. this.animationGroups.forEach(function (o) {
  29364. _this.scene.addAnimationGroup(o);
  29365. });
  29366. this.multiMaterials.forEach(function (o) {
  29367. _this.scene.addMultiMaterial(o);
  29368. });
  29369. this.materials.forEach(function (o) {
  29370. _this.scene.addMaterial(o);
  29371. });
  29372. this.morphTargetManagers.forEach(function (o) {
  29373. _this.scene.addMorphTargetManager(o);
  29374. });
  29375. this.geometries.forEach(function (o) {
  29376. _this.scene.addGeometry(o);
  29377. });
  29378. this.transformNodes.forEach(function (o) {
  29379. _this.scene.addTransformNode(o);
  29380. });
  29381. this.actionManagers.forEach(function (o) {
  29382. _this.scene.addActionManager(o);
  29383. });
  29384. this.sounds.forEach(function (o) {
  29385. o.play();
  29386. o.autoplay = true;
  29387. _this.scene.mainSoundTrack.AddSound(o);
  29388. });
  29389. this.textures.forEach(function (o) {
  29390. _this.scene.addTexture(o);
  29391. });
  29392. for (var _i = 0, _a = this.scene._components; _i < _a.length; _i++) {
  29393. var component = _a[_i];
  29394. component.addFromContainer(this.scene);
  29395. }
  29396. };
  29397. /**
  29398. * Removes all the assets in the container from the scene
  29399. */
  29400. AssetContainer.prototype.removeAllFromScene = function () {
  29401. var _this = this;
  29402. this.cameras.forEach(function (o) {
  29403. _this.scene.removeCamera(o);
  29404. });
  29405. this.lights.forEach(function (o) {
  29406. _this.scene.removeLight(o);
  29407. });
  29408. this.meshes.forEach(function (o) {
  29409. _this.scene.removeMesh(o);
  29410. });
  29411. this.skeletons.forEach(function (o) {
  29412. _this.scene.removeSkeleton(o);
  29413. });
  29414. this.particleSystems.forEach(function (o) {
  29415. _this.scene.removeParticleSystem(o);
  29416. });
  29417. this.animations.forEach(function (o) {
  29418. _this.scene.removeAnimation(o);
  29419. });
  29420. this.animationGroups.forEach(function (o) {
  29421. _this.scene.removeAnimationGroup(o);
  29422. });
  29423. this.multiMaterials.forEach(function (o) {
  29424. _this.scene.removeMultiMaterial(o);
  29425. });
  29426. this.materials.forEach(function (o) {
  29427. _this.scene.removeMaterial(o);
  29428. });
  29429. this.morphTargetManagers.forEach(function (o) {
  29430. _this.scene.removeMorphTargetManager(o);
  29431. });
  29432. this.geometries.forEach(function (o) {
  29433. _this.scene.removeGeometry(o);
  29434. });
  29435. this.transformNodes.forEach(function (o) {
  29436. _this.scene.removeTransformNode(o);
  29437. });
  29438. this.actionManagers.forEach(function (o) {
  29439. _this.scene.removeActionManager(o);
  29440. });
  29441. this.sounds.forEach(function (o) {
  29442. o.stop();
  29443. o.autoplay = false;
  29444. _this.scene.mainSoundTrack.RemoveSound(o);
  29445. });
  29446. this.textures.forEach(function (o) {
  29447. _this.scene.removeTexture(o);
  29448. });
  29449. for (var _i = 0, _a = this.scene._components; _i < _a.length; _i++) {
  29450. var component = _a[_i];
  29451. component.removeFromContainer(this.scene);
  29452. }
  29453. };
  29454. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29455. if (!sourceAssets) {
  29456. return;
  29457. }
  29458. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29459. var asset = sourceAssets_1[_i];
  29460. var move = true;
  29461. if (keepAssets) {
  29462. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29463. var keepAsset = keepAssets_1[_a];
  29464. if (asset === keepAsset) {
  29465. move = false;
  29466. break;
  29467. }
  29468. }
  29469. }
  29470. if (move) {
  29471. targetAssets.push(asset);
  29472. }
  29473. }
  29474. };
  29475. /**
  29476. * Removes all the assets contained in the scene and adds them to the container.
  29477. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29478. */
  29479. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29480. if (keepAssets === undefined) {
  29481. keepAssets = new KeepAssets();
  29482. }
  29483. for (var key in this) {
  29484. if (this.hasOwnProperty(key)) {
  29485. this[key] = this[key] || [];
  29486. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29487. }
  29488. }
  29489. this.removeAllFromScene();
  29490. };
  29491. /**
  29492. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29493. * @returns the root mesh
  29494. */
  29495. AssetContainer.prototype.createRootMesh = function () {
  29496. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29497. this.meshes.forEach(function (m) {
  29498. if (!m.parent) {
  29499. rootMesh.addChild(m);
  29500. }
  29501. });
  29502. this.meshes.unshift(rootMesh);
  29503. return rootMesh;
  29504. };
  29505. return AssetContainer;
  29506. }(BABYLON.AbstractScene));
  29507. BABYLON.AssetContainer = AssetContainer;
  29508. })(BABYLON || (BABYLON = {}));
  29509. //# sourceMappingURL=babylon.assetContainer.js.map
  29510. var BABYLON;
  29511. (function (BABYLON) {
  29512. var Buffer = /** @class */ (function () {
  29513. /**
  29514. * Constructor
  29515. * @param engine the engine
  29516. * @param data the data to use for this buffer
  29517. * @param updatable whether the data is updatable
  29518. * @param stride the stride (optional)
  29519. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29520. * @param instanced whether the buffer is instanced (optional)
  29521. * @param useBytes set to true if the stride in in bytes (optional)
  29522. */
  29523. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29524. if (stride === void 0) { stride = 0; }
  29525. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29526. if (instanced === void 0) { instanced = false; }
  29527. if (useBytes === void 0) { useBytes = false; }
  29528. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29529. this._engine = engine.getScene().getEngine();
  29530. }
  29531. else {
  29532. this._engine = engine;
  29533. }
  29534. this._updatable = updatable;
  29535. this._instanced = instanced;
  29536. this._data = data;
  29537. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29538. if (!postponeInternalCreation) { // by default
  29539. this.create();
  29540. }
  29541. }
  29542. /**
  29543. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29544. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29545. * @param offset defines offset in the buffer (0 by default)
  29546. * @param size defines the size in floats of attributes (position is 3 for instance)
  29547. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29548. * @param instanced defines if the vertex buffer contains indexed data
  29549. * @param useBytes defines if the offset and stride are in bytes
  29550. * @returns the new vertex buffer
  29551. */
  29552. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29553. if (useBytes === void 0) { useBytes = false; }
  29554. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29555. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29556. // a lot of these parameters are ignored as they are overriden by the buffer
  29557. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29558. };
  29559. // Properties
  29560. Buffer.prototype.isUpdatable = function () {
  29561. return this._updatable;
  29562. };
  29563. Buffer.prototype.getData = function () {
  29564. return this._data;
  29565. };
  29566. Buffer.prototype.getBuffer = function () {
  29567. return this._buffer;
  29568. };
  29569. /**
  29570. * Gets the stride in float32 units (i.e. byte stride / 4).
  29571. * May not be an integer if the byte stride is not divisible by 4.
  29572. * DEPRECATED. Use byteStride instead.
  29573. * @returns the stride in float32 units
  29574. */
  29575. Buffer.prototype.getStrideSize = function () {
  29576. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29577. };
  29578. // Methods
  29579. Buffer.prototype.create = function (data) {
  29580. if (data === void 0) { data = null; }
  29581. if (!data && this._buffer) {
  29582. return; // nothing to do
  29583. }
  29584. data = data || this._data;
  29585. if (!data) {
  29586. return;
  29587. }
  29588. if (!this._buffer) { // create buffer
  29589. if (this._updatable) {
  29590. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29591. this._data = data;
  29592. }
  29593. else {
  29594. this._buffer = this._engine.createVertexBuffer(data);
  29595. }
  29596. }
  29597. else if (this._updatable) { // update buffer
  29598. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29599. this._data = data;
  29600. }
  29601. };
  29602. Buffer.prototype._rebuild = function () {
  29603. this._buffer = null;
  29604. this.create(this._data);
  29605. };
  29606. Buffer.prototype.update = function (data) {
  29607. this.create(data);
  29608. };
  29609. /**
  29610. * Updates the data directly.
  29611. * @param data the new data
  29612. * @param offset the new offset
  29613. * @param vertexCount the vertex count (optional)
  29614. * @param useBytes set to true if the offset is in bytes
  29615. */
  29616. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29617. if (useBytes === void 0) { useBytes = false; }
  29618. if (!this._buffer) {
  29619. return;
  29620. }
  29621. if (this._updatable) { // update buffer
  29622. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29623. this._data = null;
  29624. }
  29625. };
  29626. Buffer.prototype.dispose = function () {
  29627. if (!this._buffer) {
  29628. return;
  29629. }
  29630. if (this._engine._releaseBuffer(this._buffer)) {
  29631. this._buffer = null;
  29632. }
  29633. };
  29634. return Buffer;
  29635. }());
  29636. BABYLON.Buffer = Buffer;
  29637. })(BABYLON || (BABYLON = {}));
  29638. //# sourceMappingURL=babylon.buffer.js.map
  29639. var BABYLON;
  29640. (function (BABYLON) {
  29641. var VertexBuffer = /** @class */ (function () {
  29642. /**
  29643. * Constructor
  29644. * @param engine the engine
  29645. * @param data the data to use for this vertex buffer
  29646. * @param kind the vertex buffer kind
  29647. * @param updatable whether the data is updatable
  29648. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29649. * @param stride the stride (optional)
  29650. * @param instanced whether the buffer is instanced (optional)
  29651. * @param offset the offset of the data (optional)
  29652. * @param size the number of components (optional)
  29653. * @param type the type of the component (optional)
  29654. * @param normalized whether the data contains normalized data (optional)
  29655. * @param useBytes set to true if stride and offset are in bytes (optional)
  29656. */
  29657. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29658. if (normalized === void 0) { normalized = false; }
  29659. if (useBytes === void 0) { useBytes = false; }
  29660. if (data instanceof BABYLON.Buffer) {
  29661. this._buffer = data;
  29662. this._ownsBuffer = false;
  29663. }
  29664. else {
  29665. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29666. this._ownsBuffer = true;
  29667. }
  29668. this._kind = kind;
  29669. if (type == undefined) {
  29670. var data_1 = this.getData();
  29671. this.type = VertexBuffer.FLOAT;
  29672. if (data_1 instanceof Int8Array)
  29673. this.type = VertexBuffer.BYTE;
  29674. else if (data_1 instanceof Uint8Array)
  29675. this.type = VertexBuffer.UNSIGNED_BYTE;
  29676. else if (data_1 instanceof Int16Array)
  29677. this.type = VertexBuffer.SHORT;
  29678. else if (data_1 instanceof Uint16Array)
  29679. this.type = VertexBuffer.UNSIGNED_SHORT;
  29680. else if (data_1 instanceof Int32Array)
  29681. this.type = VertexBuffer.INT;
  29682. else if (data_1 instanceof Uint32Array)
  29683. this.type = VertexBuffer.UNSIGNED_INT;
  29684. }
  29685. else {
  29686. this.type = type;
  29687. }
  29688. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29689. if (useBytes) {
  29690. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29691. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29692. this.byteOffset = offset || 0;
  29693. }
  29694. else {
  29695. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29696. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29697. this.byteOffset = (offset || 0) * typeByteLength;
  29698. }
  29699. this.normalized = normalized;
  29700. this._instanced = instanced !== undefined ? instanced : false;
  29701. this._instanceDivisor = instanced ? 1 : 0;
  29702. }
  29703. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29704. /**
  29705. * Gets or sets the instance divisor when in instanced mode
  29706. */
  29707. get: function () {
  29708. return this._instanceDivisor;
  29709. },
  29710. set: function (value) {
  29711. this._instanceDivisor = value;
  29712. if (value == 0) {
  29713. this._instanced = false;
  29714. }
  29715. else {
  29716. this._instanced = true;
  29717. }
  29718. },
  29719. enumerable: true,
  29720. configurable: true
  29721. });
  29722. VertexBuffer.prototype._rebuild = function () {
  29723. if (!this._buffer) {
  29724. return;
  29725. }
  29726. this._buffer._rebuild();
  29727. };
  29728. /**
  29729. * Returns the kind of the VertexBuffer (string).
  29730. */
  29731. VertexBuffer.prototype.getKind = function () {
  29732. return this._kind;
  29733. };
  29734. // Properties
  29735. /**
  29736. * Boolean : is the VertexBuffer updatable ?
  29737. */
  29738. VertexBuffer.prototype.isUpdatable = function () {
  29739. return this._buffer.isUpdatable();
  29740. };
  29741. /**
  29742. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29743. */
  29744. VertexBuffer.prototype.getData = function () {
  29745. return this._buffer.getData();
  29746. };
  29747. /**
  29748. * Returns the WebGLBuffer associated to the VertexBuffer.
  29749. */
  29750. VertexBuffer.prototype.getBuffer = function () {
  29751. return this._buffer.getBuffer();
  29752. };
  29753. /**
  29754. * Returns the stride as a multiple of the type byte length.
  29755. * DEPRECATED. Use byteStride instead.
  29756. */
  29757. VertexBuffer.prototype.getStrideSize = function () {
  29758. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29759. };
  29760. /**
  29761. * Returns the offset as a multiple of the type byte length.
  29762. * DEPRECATED. Use byteOffset instead.
  29763. */
  29764. VertexBuffer.prototype.getOffset = function () {
  29765. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29766. };
  29767. /**
  29768. * Returns the number of components per vertex attribute (integer).
  29769. */
  29770. VertexBuffer.prototype.getSize = function () {
  29771. return this._size;
  29772. };
  29773. /**
  29774. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29775. */
  29776. VertexBuffer.prototype.getIsInstanced = function () {
  29777. return this._instanced;
  29778. };
  29779. /**
  29780. * Returns the instancing divisor, zero for non-instanced (integer).
  29781. */
  29782. VertexBuffer.prototype.getInstanceDivisor = function () {
  29783. return this._instanceDivisor;
  29784. };
  29785. // Methods
  29786. /**
  29787. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29788. * Returns the created WebGLBuffer.
  29789. */
  29790. VertexBuffer.prototype.create = function (data) {
  29791. return this._buffer.create(data);
  29792. };
  29793. /**
  29794. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29795. * This function will create a new buffer if the current one is not updatable
  29796. * Returns the updated WebGLBuffer.
  29797. */
  29798. VertexBuffer.prototype.update = function (data) {
  29799. return this._buffer.update(data);
  29800. };
  29801. /**
  29802. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29803. * Returns the directly updated WebGLBuffer.
  29804. * @param data the new data
  29805. * @param offset the new offset
  29806. * @param useBytes set to true if the offset is in bytes
  29807. */
  29808. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29809. if (useBytes === void 0) { useBytes = false; }
  29810. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29811. };
  29812. /**
  29813. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29814. */
  29815. VertexBuffer.prototype.dispose = function () {
  29816. if (this._ownsBuffer) {
  29817. this._buffer.dispose();
  29818. }
  29819. };
  29820. /**
  29821. * Enumerates each value of this vertex buffer as numbers.
  29822. * @param count the number of values to enumerate
  29823. * @param callback the callback function called for each value
  29824. */
  29825. VertexBuffer.prototype.forEach = function (count, callback) {
  29826. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29827. };
  29828. Object.defineProperty(VertexBuffer, "PositionKind", {
  29829. get: function () {
  29830. return VertexBuffer._PositionKind;
  29831. },
  29832. enumerable: true,
  29833. configurable: true
  29834. });
  29835. Object.defineProperty(VertexBuffer, "NormalKind", {
  29836. get: function () {
  29837. return VertexBuffer._NormalKind;
  29838. },
  29839. enumerable: true,
  29840. configurable: true
  29841. });
  29842. Object.defineProperty(VertexBuffer, "TangentKind", {
  29843. get: function () {
  29844. return VertexBuffer._TangentKind;
  29845. },
  29846. enumerable: true,
  29847. configurable: true
  29848. });
  29849. Object.defineProperty(VertexBuffer, "UVKind", {
  29850. get: function () {
  29851. return VertexBuffer._UVKind;
  29852. },
  29853. enumerable: true,
  29854. configurable: true
  29855. });
  29856. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29857. get: function () {
  29858. return VertexBuffer._UV2Kind;
  29859. },
  29860. enumerable: true,
  29861. configurable: true
  29862. });
  29863. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29864. get: function () {
  29865. return VertexBuffer._UV3Kind;
  29866. },
  29867. enumerable: true,
  29868. configurable: true
  29869. });
  29870. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29871. get: function () {
  29872. return VertexBuffer._UV4Kind;
  29873. },
  29874. enumerable: true,
  29875. configurable: true
  29876. });
  29877. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29878. get: function () {
  29879. return VertexBuffer._UV5Kind;
  29880. },
  29881. enumerable: true,
  29882. configurable: true
  29883. });
  29884. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29885. get: function () {
  29886. return VertexBuffer._UV6Kind;
  29887. },
  29888. enumerable: true,
  29889. configurable: true
  29890. });
  29891. Object.defineProperty(VertexBuffer, "ColorKind", {
  29892. get: function () {
  29893. return VertexBuffer._ColorKind;
  29894. },
  29895. enumerable: true,
  29896. configurable: true
  29897. });
  29898. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29899. get: function () {
  29900. return VertexBuffer._MatricesIndicesKind;
  29901. },
  29902. enumerable: true,
  29903. configurable: true
  29904. });
  29905. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29906. get: function () {
  29907. return VertexBuffer._MatricesWeightsKind;
  29908. },
  29909. enumerable: true,
  29910. configurable: true
  29911. });
  29912. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29913. get: function () {
  29914. return VertexBuffer._MatricesIndicesExtraKind;
  29915. },
  29916. enumerable: true,
  29917. configurable: true
  29918. });
  29919. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29920. get: function () {
  29921. return VertexBuffer._MatricesWeightsExtraKind;
  29922. },
  29923. enumerable: true,
  29924. configurable: true
  29925. });
  29926. /**
  29927. * Deduces the stride given a kind.
  29928. * @param kind The kind string to deduce
  29929. * @returns The deduced stride
  29930. */
  29931. VertexBuffer.DeduceStride = function (kind) {
  29932. switch (kind) {
  29933. case VertexBuffer.UVKind:
  29934. case VertexBuffer.UV2Kind:
  29935. case VertexBuffer.UV3Kind:
  29936. case VertexBuffer.UV4Kind:
  29937. case VertexBuffer.UV5Kind:
  29938. case VertexBuffer.UV6Kind:
  29939. return 2;
  29940. case VertexBuffer.NormalKind:
  29941. case VertexBuffer.PositionKind:
  29942. return 3;
  29943. case VertexBuffer.ColorKind:
  29944. case VertexBuffer.MatricesIndicesKind:
  29945. case VertexBuffer.MatricesIndicesExtraKind:
  29946. case VertexBuffer.MatricesWeightsKind:
  29947. case VertexBuffer.MatricesWeightsExtraKind:
  29948. case VertexBuffer.TangentKind:
  29949. return 4;
  29950. default:
  29951. throw new Error("Invalid kind '" + kind + "'");
  29952. }
  29953. };
  29954. /**
  29955. * Gets the byte length of the given type.
  29956. * @param type the type
  29957. * @returns the number of bytes
  29958. */
  29959. VertexBuffer.GetTypeByteLength = function (type) {
  29960. switch (type) {
  29961. case VertexBuffer.BYTE:
  29962. case VertexBuffer.UNSIGNED_BYTE:
  29963. return 1;
  29964. case VertexBuffer.SHORT:
  29965. case VertexBuffer.UNSIGNED_SHORT:
  29966. return 2;
  29967. case VertexBuffer.INT:
  29968. case VertexBuffer.FLOAT:
  29969. return 4;
  29970. default:
  29971. throw new Error("Invalid type '" + type + "'");
  29972. }
  29973. };
  29974. /**
  29975. * Enumerates each value of the given parameters as numbers.
  29976. * @param data the data to enumerate
  29977. * @param byteOffset the byte offset of the data
  29978. * @param byteStride the byte stride of the data
  29979. * @param componentCount the number of components per element
  29980. * @param componentType the type of the component
  29981. * @param count the total number of components
  29982. * @param normalized whether the data is normalized
  29983. * @param callback the callback function called for each value
  29984. */
  29985. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29986. if (data instanceof Array) {
  29987. var offset = byteOffset / 4;
  29988. var stride = byteStride / 4;
  29989. for (var index = 0; index < count; index += componentCount) {
  29990. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29991. callback(data[offset + componentIndex], index + componentIndex);
  29992. }
  29993. offset += stride;
  29994. }
  29995. }
  29996. else {
  29997. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29998. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29999. for (var index = 0; index < count; index += componentCount) {
  30000. var componentByteOffset = byteOffset;
  30001. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30002. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30003. callback(value, index + componentIndex);
  30004. componentByteOffset += componentByteLength;
  30005. }
  30006. byteOffset += byteStride;
  30007. }
  30008. }
  30009. };
  30010. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30011. switch (type) {
  30012. case VertexBuffer.BYTE: {
  30013. var value = dataView.getInt8(byteOffset);
  30014. if (normalized) {
  30015. value = Math.max(value / 127, -1);
  30016. }
  30017. return value;
  30018. }
  30019. case VertexBuffer.UNSIGNED_BYTE: {
  30020. var value = dataView.getUint8(byteOffset);
  30021. if (normalized) {
  30022. value = value / 255;
  30023. }
  30024. return value;
  30025. }
  30026. case VertexBuffer.SHORT: {
  30027. var value = dataView.getInt16(byteOffset, true);
  30028. if (normalized) {
  30029. value = Math.max(value / 16383, -1);
  30030. }
  30031. return value;
  30032. }
  30033. case VertexBuffer.UNSIGNED_SHORT: {
  30034. var value = dataView.getUint16(byteOffset, true);
  30035. if (normalized) {
  30036. value = value / 65535;
  30037. }
  30038. return value;
  30039. }
  30040. case VertexBuffer.FLOAT: {
  30041. return dataView.getFloat32(byteOffset, true);
  30042. }
  30043. default: {
  30044. throw new Error("Invalid component type " + type);
  30045. }
  30046. }
  30047. };
  30048. /**
  30049. * The byte type.
  30050. */
  30051. VertexBuffer.BYTE = 5120;
  30052. /**
  30053. * The unsigned byte type.
  30054. */
  30055. VertexBuffer.UNSIGNED_BYTE = 5121;
  30056. /**
  30057. * The short type.
  30058. */
  30059. VertexBuffer.SHORT = 5122;
  30060. /**
  30061. * The unsigned short type.
  30062. */
  30063. VertexBuffer.UNSIGNED_SHORT = 5123;
  30064. /**
  30065. * The integer type.
  30066. */
  30067. VertexBuffer.INT = 5124;
  30068. /**
  30069. * The unsigned integer type.
  30070. */
  30071. VertexBuffer.UNSIGNED_INT = 5125;
  30072. /**
  30073. * The float type.
  30074. */
  30075. VertexBuffer.FLOAT = 5126;
  30076. // Enums
  30077. VertexBuffer._PositionKind = "position";
  30078. VertexBuffer._NormalKind = "normal";
  30079. VertexBuffer._TangentKind = "tangent";
  30080. VertexBuffer._UVKind = "uv";
  30081. VertexBuffer._UV2Kind = "uv2";
  30082. VertexBuffer._UV3Kind = "uv3";
  30083. VertexBuffer._UV4Kind = "uv4";
  30084. VertexBuffer._UV5Kind = "uv5";
  30085. VertexBuffer._UV6Kind = "uv6";
  30086. VertexBuffer._ColorKind = "color";
  30087. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30088. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30089. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30090. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30091. return VertexBuffer;
  30092. }());
  30093. BABYLON.VertexBuffer = VertexBuffer;
  30094. })(BABYLON || (BABYLON = {}));
  30095. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30096. var BABYLON;
  30097. (function (BABYLON) {
  30098. /**
  30099. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30100. */
  30101. var DummyInternalTextureTracker = /** @class */ (function () {
  30102. function DummyInternalTextureTracker() {
  30103. /**
  30104. * Gets or set the previous tracker in the list
  30105. */
  30106. this.previous = null;
  30107. /**
  30108. * Gets or set the next tracker in the list
  30109. */
  30110. this.next = null;
  30111. }
  30112. return DummyInternalTextureTracker;
  30113. }());
  30114. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30115. })(BABYLON || (BABYLON = {}));
  30116. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30117. var BABYLON;
  30118. (function (BABYLON) {
  30119. /**
  30120. * Class used to store data associated with WebGL texture data for the engine
  30121. * This class should not be used directly
  30122. */
  30123. var InternalTexture = /** @class */ (function () {
  30124. /**
  30125. * Creates a new InternalTexture
  30126. * @param engine defines the engine to use
  30127. * @param dataSource defines the type of data that will be used
  30128. */
  30129. function InternalTexture(engine, dataSource) {
  30130. /**
  30131. * Observable called when the texture is loaded
  30132. */
  30133. this.onLoadedObservable = new BABYLON.Observable();
  30134. /**
  30135. * Gets or set the previous tracker in the list
  30136. */
  30137. this.previous = null;
  30138. /**
  30139. * Gets or set the next tracker in the list
  30140. */
  30141. this.next = null;
  30142. // Private
  30143. /** @hidden */
  30144. this._initialSlot = -1;
  30145. /** @hidden */
  30146. this._designatedSlot = -1;
  30147. /** @hidden */
  30148. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30149. /** @hidden */
  30150. this._comparisonFunction = 0;
  30151. /** @hidden */
  30152. this._lodGenerationScale = 0;
  30153. /** @hidden */
  30154. this._lodGenerationOffset = 0;
  30155. /** @hidden */
  30156. this._isRGBD = false;
  30157. /** @hidden */
  30158. this._references = 1;
  30159. this._engine = engine;
  30160. this._dataSource = dataSource;
  30161. this._webGLTexture = engine._createTexture();
  30162. }
  30163. /**
  30164. * Gets the Engine the texture belongs to.
  30165. * @returns The babylon engine
  30166. */
  30167. InternalTexture.prototype.getEngine = function () {
  30168. return this._engine;
  30169. };
  30170. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30171. /**
  30172. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30173. */
  30174. get: function () {
  30175. return this._dataSource;
  30176. },
  30177. enumerable: true,
  30178. configurable: true
  30179. });
  30180. /**
  30181. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30182. */
  30183. InternalTexture.prototype.incrementReferences = function () {
  30184. this._references++;
  30185. };
  30186. /**
  30187. * Change the size of the texture (not the size of the content)
  30188. * @param width defines the new width
  30189. * @param height defines the new height
  30190. * @param depth defines the new depth (1 by default)
  30191. */
  30192. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30193. if (depth === void 0) { depth = 1; }
  30194. this.width = width;
  30195. this.height = height;
  30196. this.depth = depth;
  30197. this.baseWidth = width;
  30198. this.baseHeight = height;
  30199. this.baseDepth = depth;
  30200. this._size = width * height * depth;
  30201. };
  30202. /** @hidden */
  30203. InternalTexture.prototype._rebuild = function () {
  30204. var _this = this;
  30205. var proxy;
  30206. this.isReady = false;
  30207. this._cachedCoordinatesMode = null;
  30208. this._cachedWrapU = null;
  30209. this._cachedWrapV = null;
  30210. this._cachedAnisotropicFilteringLevel = null;
  30211. switch (this._dataSource) {
  30212. case InternalTexture.DATASOURCE_TEMP:
  30213. return;
  30214. case InternalTexture.DATASOURCE_URL:
  30215. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30216. _this.isReady = true;
  30217. }, null, this._buffer, undefined, this.format);
  30218. proxy._swapAndDie(this);
  30219. return;
  30220. case InternalTexture.DATASOURCE_RAW:
  30221. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30222. proxy._swapAndDie(this);
  30223. this.isReady = true;
  30224. return;
  30225. case InternalTexture.DATASOURCE_RAW3D:
  30226. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30227. proxy._swapAndDie(this);
  30228. this.isReady = true;
  30229. return;
  30230. case InternalTexture.DATASOURCE_DYNAMIC:
  30231. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30232. proxy._swapAndDie(this);
  30233. // The engine will make sure to update content so no need to flag it as isReady = true
  30234. return;
  30235. case InternalTexture.DATASOURCE_RENDERTARGET:
  30236. var options = new BABYLON.RenderTargetCreationOptions();
  30237. options.generateDepthBuffer = this._generateDepthBuffer;
  30238. options.generateMipMaps = this.generateMipMaps;
  30239. options.generateStencilBuffer = this._generateStencilBuffer;
  30240. options.samplingMode = this.samplingMode;
  30241. options.type = this.type;
  30242. if (this.isCube) {
  30243. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30244. }
  30245. else {
  30246. var size = {
  30247. width: this.width,
  30248. height: this.height
  30249. };
  30250. proxy = this._engine.createRenderTargetTexture(size, options);
  30251. }
  30252. proxy._swapAndDie(this);
  30253. this.isReady = true;
  30254. return;
  30255. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30256. var depthTextureOptions = {
  30257. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30258. comparisonFunction: this._comparisonFunction,
  30259. generateStencil: this._generateStencilBuffer,
  30260. isCube: this.isCube
  30261. };
  30262. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30263. proxy._swapAndDie(this);
  30264. this.isReady = true;
  30265. return;
  30266. case InternalTexture.DATASOURCE_CUBE:
  30267. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30268. _this.isReady = true;
  30269. }, null, this.format, this._extension);
  30270. proxy._swapAndDie(this);
  30271. return;
  30272. case InternalTexture.DATASOURCE_CUBERAW:
  30273. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30274. proxy._swapAndDie(this);
  30275. this.isReady = true;
  30276. return;
  30277. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30278. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30279. if (proxy) {
  30280. proxy._swapAndDie(_this);
  30281. }
  30282. _this.isReady = true;
  30283. }, null, this.format, this._extension);
  30284. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30285. return;
  30286. }
  30287. };
  30288. InternalTexture.prototype._swapAndDie = function (target) {
  30289. target._webGLTexture = this._webGLTexture;
  30290. if (this._framebuffer) {
  30291. target._framebuffer = this._framebuffer;
  30292. }
  30293. if (this._depthStencilBuffer) {
  30294. target._depthStencilBuffer = this._depthStencilBuffer;
  30295. }
  30296. if (this._lodTextureHigh) {
  30297. if (target._lodTextureHigh) {
  30298. target._lodTextureHigh.dispose();
  30299. }
  30300. target._lodTextureHigh = this._lodTextureHigh;
  30301. }
  30302. if (this._lodTextureMid) {
  30303. if (target._lodTextureMid) {
  30304. target._lodTextureMid.dispose();
  30305. }
  30306. target._lodTextureMid = this._lodTextureMid;
  30307. }
  30308. if (this._lodTextureLow) {
  30309. if (target._lodTextureLow) {
  30310. target._lodTextureLow.dispose();
  30311. }
  30312. target._lodTextureLow = this._lodTextureLow;
  30313. }
  30314. var cache = this._engine.getLoadedTexturesCache();
  30315. var index = cache.indexOf(this);
  30316. if (index !== -1) {
  30317. cache.splice(index, 1);
  30318. }
  30319. };
  30320. /**
  30321. * Dispose the current allocated resources
  30322. */
  30323. InternalTexture.prototype.dispose = function () {
  30324. if (!this._webGLTexture) {
  30325. return;
  30326. }
  30327. this._references--;
  30328. if (this._references === 0) {
  30329. this._engine._releaseTexture(this);
  30330. this._webGLTexture = null;
  30331. this.previous = null;
  30332. this.next = null;
  30333. }
  30334. };
  30335. /**
  30336. * The source of the texture data is unknown
  30337. */
  30338. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30339. /**
  30340. * Texture data comes from an URL
  30341. */
  30342. InternalTexture.DATASOURCE_URL = 1;
  30343. /**
  30344. * Texture data is only used for temporary storage
  30345. */
  30346. InternalTexture.DATASOURCE_TEMP = 2;
  30347. /**
  30348. * Texture data comes from raw data (ArrayBuffer)
  30349. */
  30350. InternalTexture.DATASOURCE_RAW = 3;
  30351. /**
  30352. * Texture content is dynamic (video or dynamic texture)
  30353. */
  30354. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30355. /**
  30356. * Texture content is generated by rendering to it
  30357. */
  30358. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30359. /**
  30360. * Texture content is part of a multi render target process
  30361. */
  30362. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30363. /**
  30364. * Texture data comes from a cube data file
  30365. */
  30366. InternalTexture.DATASOURCE_CUBE = 7;
  30367. /**
  30368. * Texture data comes from a raw cube data
  30369. */
  30370. InternalTexture.DATASOURCE_CUBERAW = 8;
  30371. /**
  30372. * Texture data come from a prefiltered cube data file
  30373. */
  30374. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30375. /**
  30376. * Texture content is raw 3D data
  30377. */
  30378. InternalTexture.DATASOURCE_RAW3D = 10;
  30379. /**
  30380. * Texture content is a depth texture
  30381. */
  30382. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30383. return InternalTexture;
  30384. }());
  30385. BABYLON.InternalTexture = InternalTexture;
  30386. })(BABYLON || (BABYLON = {}));
  30387. //# sourceMappingURL=babylon.internalTexture.js.map
  30388. var BABYLON;
  30389. (function (BABYLON) {
  30390. var BaseTexture = /** @class */ (function () {
  30391. function BaseTexture(scene) {
  30392. this._hasAlpha = false;
  30393. this.getAlphaFromRGB = false;
  30394. this.level = 1;
  30395. this.coordinatesIndex = 0;
  30396. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30397. /**
  30398. * | Value | Type | Description |
  30399. * | ----- | ------------------ | ----------- |
  30400. * | 0 | CLAMP_ADDRESSMODE | |
  30401. * | 1 | WRAP_ADDRESSMODE | |
  30402. * | 2 | MIRROR_ADDRESSMODE | |
  30403. */
  30404. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30405. /**
  30406. * | Value | Type | Description |
  30407. * | ----- | ------------------ | ----------- |
  30408. * | 0 | CLAMP_ADDRESSMODE | |
  30409. * | 1 | WRAP_ADDRESSMODE | |
  30410. * | 2 | MIRROR_ADDRESSMODE | |
  30411. */
  30412. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30413. /**
  30414. * | Value | Type | Description |
  30415. * | ----- | ------------------ | ----------- |
  30416. * | 0 | CLAMP_ADDRESSMODE | |
  30417. * | 1 | WRAP_ADDRESSMODE | |
  30418. * | 2 | MIRROR_ADDRESSMODE | |
  30419. */
  30420. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30421. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30422. this.isCube = false;
  30423. this.is3D = false;
  30424. this.gammaSpace = true;
  30425. this.invertZ = false;
  30426. this.lodLevelInAlpha = false;
  30427. this.isRenderTarget = false;
  30428. this.animations = new Array();
  30429. /**
  30430. * An event triggered when the texture is disposed.
  30431. */
  30432. this.onDisposeObservable = new BABYLON.Observable();
  30433. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30434. this._cachedSize = BABYLON.Size.Zero();
  30435. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30436. if (this._scene) {
  30437. this._scene.textures.push(this);
  30438. }
  30439. this._uid = null;
  30440. }
  30441. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30442. get: function () {
  30443. return this._hasAlpha;
  30444. },
  30445. set: function (value) {
  30446. if (this._hasAlpha === value) {
  30447. return;
  30448. }
  30449. this._hasAlpha = value;
  30450. if (this._scene) {
  30451. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30452. }
  30453. },
  30454. enumerable: true,
  30455. configurable: true
  30456. });
  30457. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30458. get: function () {
  30459. return this._coordinatesMode;
  30460. },
  30461. /**
  30462. * How a texture is mapped.
  30463. *
  30464. * | Value | Type | Description |
  30465. * | ----- | ----------------------------------- | ----------- |
  30466. * | 0 | EXPLICIT_MODE | |
  30467. * | 1 | SPHERICAL_MODE | |
  30468. * | 2 | PLANAR_MODE | |
  30469. * | 3 | CUBIC_MODE | |
  30470. * | 4 | PROJECTION_MODE | |
  30471. * | 5 | SKYBOX_MODE | |
  30472. * | 6 | INVCUBIC_MODE | |
  30473. * | 7 | EQUIRECTANGULAR_MODE | |
  30474. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30475. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30476. */
  30477. set: function (value) {
  30478. if (this._coordinatesMode === value) {
  30479. return;
  30480. }
  30481. this._coordinatesMode = value;
  30482. if (this._scene) {
  30483. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30484. }
  30485. },
  30486. enumerable: true,
  30487. configurable: true
  30488. });
  30489. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30490. /**
  30491. * Gets whether or not the texture contains RGBD data.
  30492. */
  30493. get: function () {
  30494. return this._texture != null && this._texture._isRGBD;
  30495. },
  30496. enumerable: true,
  30497. configurable: true
  30498. });
  30499. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30500. get: function () {
  30501. if (this._texture)
  30502. return this._texture._lodGenerationOffset;
  30503. return 0.0;
  30504. },
  30505. set: function (value) {
  30506. if (this._texture)
  30507. this._texture._lodGenerationOffset = value;
  30508. },
  30509. enumerable: true,
  30510. configurable: true
  30511. });
  30512. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30513. get: function () {
  30514. if (this._texture)
  30515. return this._texture._lodGenerationScale;
  30516. return 0.0;
  30517. },
  30518. set: function (value) {
  30519. if (this._texture)
  30520. this._texture._lodGenerationScale = value;
  30521. },
  30522. enumerable: true,
  30523. configurable: true
  30524. });
  30525. Object.defineProperty(BaseTexture.prototype, "uid", {
  30526. get: function () {
  30527. if (!this._uid) {
  30528. this._uid = BABYLON.Tools.RandomId();
  30529. }
  30530. return this._uid;
  30531. },
  30532. enumerable: true,
  30533. configurable: true
  30534. });
  30535. BaseTexture.prototype.toString = function () {
  30536. return this.name;
  30537. };
  30538. BaseTexture.prototype.getClassName = function () {
  30539. return "BaseTexture";
  30540. };
  30541. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30542. set: function (callback) {
  30543. if (this._onDisposeObserver) {
  30544. this.onDisposeObservable.remove(this._onDisposeObserver);
  30545. }
  30546. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30547. },
  30548. enumerable: true,
  30549. configurable: true
  30550. });
  30551. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30552. get: function () {
  30553. return true;
  30554. },
  30555. enumerable: true,
  30556. configurable: true
  30557. });
  30558. BaseTexture.prototype.getScene = function () {
  30559. return this._scene;
  30560. };
  30561. BaseTexture.prototype.getTextureMatrix = function () {
  30562. return BABYLON.Matrix.IdentityReadOnly;
  30563. };
  30564. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30565. return BABYLON.Matrix.IdentityReadOnly;
  30566. };
  30567. BaseTexture.prototype.getInternalTexture = function () {
  30568. return this._texture;
  30569. };
  30570. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30571. return !this.isBlocking || this.isReady();
  30572. };
  30573. BaseTexture.prototype.isReady = function () {
  30574. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30575. this.delayLoad();
  30576. return false;
  30577. }
  30578. if (this._texture) {
  30579. return this._texture.isReady;
  30580. }
  30581. return false;
  30582. };
  30583. BaseTexture.prototype.getSize = function () {
  30584. if (this._texture) {
  30585. if (this._texture.width) {
  30586. this._cachedSize.width = this._texture.width;
  30587. this._cachedSize.height = this._texture.height;
  30588. return this._cachedSize;
  30589. }
  30590. if (this._texture._size) {
  30591. this._cachedSize.width = this._texture._size;
  30592. this._cachedSize.height = this._texture._size;
  30593. return this._cachedSize;
  30594. }
  30595. }
  30596. return this._cachedSize;
  30597. };
  30598. BaseTexture.prototype.getBaseSize = function () {
  30599. if (!this.isReady() || !this._texture)
  30600. return BABYLON.Size.Zero();
  30601. if (this._texture._size) {
  30602. return new BABYLON.Size(this._texture._size, this._texture._size);
  30603. }
  30604. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30605. };
  30606. BaseTexture.prototype.scale = function (ratio) {
  30607. };
  30608. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30609. get: function () {
  30610. return false;
  30611. },
  30612. enumerable: true,
  30613. configurable: true
  30614. });
  30615. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30616. if (!this._scene) {
  30617. return null;
  30618. }
  30619. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30620. for (var index = 0; index < texturesCache.length; index++) {
  30621. var texturesCacheEntry = texturesCache[index];
  30622. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30623. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30624. texturesCacheEntry.incrementReferences();
  30625. return texturesCacheEntry;
  30626. }
  30627. }
  30628. }
  30629. return null;
  30630. };
  30631. BaseTexture.prototype._rebuild = function () {
  30632. };
  30633. BaseTexture.prototype.delayLoad = function () {
  30634. };
  30635. BaseTexture.prototype.clone = function () {
  30636. return null;
  30637. };
  30638. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30639. get: function () {
  30640. if (!this._texture) {
  30641. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30642. }
  30643. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30644. },
  30645. enumerable: true,
  30646. configurable: true
  30647. });
  30648. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30649. get: function () {
  30650. if (!this._texture) {
  30651. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30652. }
  30653. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30654. },
  30655. enumerable: true,
  30656. configurable: true
  30657. });
  30658. /**
  30659. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30660. * This will returns an RGBA array buffer containing either in values (0-255) or
  30661. * float values (0-1) depending of the underlying buffer type.
  30662. * @param faceIndex The face of the texture to read (in case of cube texture)
  30663. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30664. * @returns The Array buffer containing the pixels data.
  30665. */
  30666. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30667. if (faceIndex === void 0) { faceIndex = 0; }
  30668. if (level === void 0) { level = 0; }
  30669. if (!this._texture) {
  30670. return null;
  30671. }
  30672. var size = this.getSize();
  30673. var width = size.width;
  30674. var height = size.height;
  30675. var scene = this.getScene();
  30676. if (!scene) {
  30677. return null;
  30678. }
  30679. var engine = scene.getEngine();
  30680. if (level != 0) {
  30681. width = width / Math.pow(2, level);
  30682. height = height / Math.pow(2, level);
  30683. width = Math.round(width);
  30684. height = Math.round(height);
  30685. }
  30686. if (this._texture.isCube) {
  30687. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30688. }
  30689. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30690. };
  30691. BaseTexture.prototype.releaseInternalTexture = function () {
  30692. if (this._texture) {
  30693. this._texture.dispose();
  30694. this._texture = null;
  30695. }
  30696. };
  30697. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30698. get: function () {
  30699. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30700. return null;
  30701. }
  30702. if (!this._texture._sphericalPolynomial) {
  30703. this._texture._sphericalPolynomial =
  30704. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30705. }
  30706. return this._texture._sphericalPolynomial;
  30707. },
  30708. set: function (value) {
  30709. if (this._texture) {
  30710. this._texture._sphericalPolynomial = value;
  30711. }
  30712. },
  30713. enumerable: true,
  30714. configurable: true
  30715. });
  30716. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30717. get: function () {
  30718. if (this._texture) {
  30719. return this._texture._lodTextureHigh;
  30720. }
  30721. return null;
  30722. },
  30723. enumerable: true,
  30724. configurable: true
  30725. });
  30726. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30727. get: function () {
  30728. if (this._texture) {
  30729. return this._texture._lodTextureMid;
  30730. }
  30731. return null;
  30732. },
  30733. enumerable: true,
  30734. configurable: true
  30735. });
  30736. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30737. get: function () {
  30738. if (this._texture) {
  30739. return this._texture._lodTextureLow;
  30740. }
  30741. return null;
  30742. },
  30743. enumerable: true,
  30744. configurable: true
  30745. });
  30746. BaseTexture.prototype.dispose = function () {
  30747. if (!this._scene) {
  30748. return;
  30749. }
  30750. // Animations
  30751. this._scene.stopAnimation(this);
  30752. // Remove from scene
  30753. this._scene._removePendingData(this);
  30754. var index = this._scene.textures.indexOf(this);
  30755. if (index >= 0) {
  30756. this._scene.textures.splice(index, 1);
  30757. }
  30758. if (this._texture === undefined) {
  30759. return;
  30760. }
  30761. // Release
  30762. this.releaseInternalTexture();
  30763. // Callback
  30764. this.onDisposeObservable.notifyObservers(this);
  30765. this.onDisposeObservable.clear();
  30766. };
  30767. BaseTexture.prototype.serialize = function () {
  30768. if (!this.name) {
  30769. return null;
  30770. }
  30771. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30772. // Animations
  30773. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30774. return serializationObject;
  30775. };
  30776. BaseTexture.WhenAllReady = function (textures, callback) {
  30777. var numRemaining = textures.length;
  30778. if (numRemaining === 0) {
  30779. callback();
  30780. return;
  30781. }
  30782. var _loop_1 = function () {
  30783. texture = textures[i];
  30784. if (texture.isReady()) {
  30785. if (--numRemaining === 0) {
  30786. callback();
  30787. }
  30788. }
  30789. else {
  30790. onLoadObservable = texture.onLoadObservable;
  30791. var onLoadCallback_1 = function () {
  30792. onLoadObservable.removeCallback(onLoadCallback_1);
  30793. if (--numRemaining === 0) {
  30794. callback();
  30795. }
  30796. };
  30797. onLoadObservable.add(onLoadCallback_1);
  30798. }
  30799. };
  30800. var texture, onLoadObservable;
  30801. for (var i = 0; i < textures.length; i++) {
  30802. _loop_1();
  30803. }
  30804. };
  30805. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30806. __decorate([
  30807. BABYLON.serialize()
  30808. ], BaseTexture.prototype, "name", void 0);
  30809. __decorate([
  30810. BABYLON.serialize("hasAlpha")
  30811. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30812. __decorate([
  30813. BABYLON.serialize()
  30814. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30815. __decorate([
  30816. BABYLON.serialize()
  30817. ], BaseTexture.prototype, "level", void 0);
  30818. __decorate([
  30819. BABYLON.serialize()
  30820. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30821. __decorate([
  30822. BABYLON.serialize("coordinatesMode")
  30823. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30824. __decorate([
  30825. BABYLON.serialize()
  30826. ], BaseTexture.prototype, "wrapU", void 0);
  30827. __decorate([
  30828. BABYLON.serialize()
  30829. ], BaseTexture.prototype, "wrapV", void 0);
  30830. __decorate([
  30831. BABYLON.serialize()
  30832. ], BaseTexture.prototype, "wrapR", void 0);
  30833. __decorate([
  30834. BABYLON.serialize()
  30835. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30836. __decorate([
  30837. BABYLON.serialize()
  30838. ], BaseTexture.prototype, "isCube", void 0);
  30839. __decorate([
  30840. BABYLON.serialize()
  30841. ], BaseTexture.prototype, "is3D", void 0);
  30842. __decorate([
  30843. BABYLON.serialize()
  30844. ], BaseTexture.prototype, "gammaSpace", void 0);
  30845. __decorate([
  30846. BABYLON.serialize()
  30847. ], BaseTexture.prototype, "invertZ", void 0);
  30848. __decorate([
  30849. BABYLON.serialize()
  30850. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30851. __decorate([
  30852. BABYLON.serialize()
  30853. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30854. __decorate([
  30855. BABYLON.serialize()
  30856. ], BaseTexture.prototype, "lodGenerationScale", null);
  30857. __decorate([
  30858. BABYLON.serialize()
  30859. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30860. return BaseTexture;
  30861. }());
  30862. BABYLON.BaseTexture = BaseTexture;
  30863. })(BABYLON || (BABYLON = {}));
  30864. //# sourceMappingURL=babylon.baseTexture.js.map
  30865. var BABYLON;
  30866. (function (BABYLON) {
  30867. var Texture = /** @class */ (function (_super) {
  30868. __extends(Texture, _super);
  30869. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30870. if (noMipmap === void 0) { noMipmap = false; }
  30871. if (invertY === void 0) { invertY = true; }
  30872. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30873. if (onLoad === void 0) { onLoad = null; }
  30874. if (onError === void 0) { onError = null; }
  30875. if (buffer === void 0) { buffer = null; }
  30876. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30877. var _this = _super.call(this, scene) || this;
  30878. _this.uOffset = 0;
  30879. _this.vOffset = 0;
  30880. _this.uScale = 1.0;
  30881. _this.vScale = 1.0;
  30882. _this.uAng = 0;
  30883. _this.vAng = 0;
  30884. _this.wAng = 0;
  30885. /**
  30886. * Defines the center of rotation (U)
  30887. */
  30888. _this.uRotationCenter = 0.5;
  30889. /**
  30890. * Defines the center of rotation (V)
  30891. */
  30892. _this.vRotationCenter = 0.5;
  30893. /**
  30894. * Defines the center of rotation (W)
  30895. */
  30896. _this.wRotationCenter = 0.5;
  30897. _this._isBlocking = true;
  30898. _this.name = url || "";
  30899. _this.url = url;
  30900. _this._noMipmap = noMipmap;
  30901. _this._invertY = invertY;
  30902. _this._samplingMode = samplingMode;
  30903. _this._buffer = buffer;
  30904. _this._deleteBuffer = deleteBuffer;
  30905. if (format) {
  30906. _this._format = format;
  30907. }
  30908. scene = _this.getScene();
  30909. if (!scene) {
  30910. return _this;
  30911. }
  30912. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30913. var load = function () {
  30914. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30915. _this.onLoadObservable.notifyObservers(_this);
  30916. }
  30917. if (onLoad) {
  30918. onLoad();
  30919. }
  30920. if (!_this.isBlocking && scene) {
  30921. scene.resetCachedMaterial();
  30922. }
  30923. };
  30924. if (!_this.url) {
  30925. _this._delayedOnLoad = load;
  30926. _this._delayedOnError = onError;
  30927. return _this;
  30928. }
  30929. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30930. if (!_this._texture) {
  30931. if (!scene.useDelayedTextureLoading) {
  30932. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30933. if (deleteBuffer) {
  30934. delete _this._buffer;
  30935. }
  30936. }
  30937. else {
  30938. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30939. _this._delayedOnLoad = load;
  30940. _this._delayedOnError = onError;
  30941. }
  30942. }
  30943. else {
  30944. if (_this._texture.isReady) {
  30945. BABYLON.Tools.SetImmediate(function () { return load(); });
  30946. }
  30947. else {
  30948. _this._texture.onLoadedObservable.add(load);
  30949. }
  30950. }
  30951. return _this;
  30952. }
  30953. Object.defineProperty(Texture.prototype, "noMipmap", {
  30954. get: function () {
  30955. return this._noMipmap;
  30956. },
  30957. enumerable: true,
  30958. configurable: true
  30959. });
  30960. Object.defineProperty(Texture.prototype, "isBlocking", {
  30961. get: function () {
  30962. return this._isBlocking;
  30963. },
  30964. set: function (value) {
  30965. this._isBlocking = value;
  30966. },
  30967. enumerable: true,
  30968. configurable: true
  30969. });
  30970. Object.defineProperty(Texture.prototype, "samplingMode", {
  30971. get: function () {
  30972. return this._samplingMode;
  30973. },
  30974. enumerable: true,
  30975. configurable: true
  30976. });
  30977. /**
  30978. * Update the url (and optional buffer) of this texture if url was null during construction.
  30979. * @param url the url of the texture
  30980. * @param buffer the buffer of the texture (defaults to null)
  30981. */
  30982. Texture.prototype.updateURL = function (url, buffer) {
  30983. if (buffer === void 0) { buffer = null; }
  30984. if (this.url) {
  30985. throw new Error("URL is already set");
  30986. }
  30987. this.url = url;
  30988. this._buffer = buffer;
  30989. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30990. this.delayLoad();
  30991. };
  30992. Texture.prototype.delayLoad = function () {
  30993. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30994. return;
  30995. }
  30996. var scene = this.getScene();
  30997. if (!scene) {
  30998. return;
  30999. }
  31000. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31001. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31002. if (!this._texture) {
  31003. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31004. if (this._deleteBuffer) {
  31005. delete this._buffer;
  31006. }
  31007. }
  31008. else {
  31009. if (this._delayedOnLoad) {
  31010. if (this._texture.isReady) {
  31011. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31012. }
  31013. else {
  31014. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31015. }
  31016. }
  31017. }
  31018. this._delayedOnLoad = null;
  31019. this._delayedOnError = null;
  31020. };
  31021. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31022. if (!this._texture) {
  31023. return;
  31024. }
  31025. var scene = this.getScene();
  31026. if (!scene) {
  31027. return;
  31028. }
  31029. this._samplingMode = samplingMode;
  31030. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31031. };
  31032. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31033. x *= this.uScale;
  31034. y *= this.vScale;
  31035. x -= this.uRotationCenter * this.uScale;
  31036. y -= this.vRotationCenter * this.vScale;
  31037. z -= this.wRotationCenter;
  31038. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31039. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31040. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31041. t.z += this.wRotationCenter;
  31042. };
  31043. Texture.prototype.getTextureMatrix = function () {
  31044. var _this = this;
  31045. if (this.uOffset === this._cachedUOffset &&
  31046. this.vOffset === this._cachedVOffset &&
  31047. this.uScale === this._cachedUScale &&
  31048. this.vScale === this._cachedVScale &&
  31049. this.uAng === this._cachedUAng &&
  31050. this.vAng === this._cachedVAng &&
  31051. this.wAng === this._cachedWAng) {
  31052. return this._cachedTextureMatrix;
  31053. }
  31054. this._cachedUOffset = this.uOffset;
  31055. this._cachedVOffset = this.vOffset;
  31056. this._cachedUScale = this.uScale;
  31057. this._cachedVScale = this.vScale;
  31058. this._cachedUAng = this.uAng;
  31059. this._cachedVAng = this.vAng;
  31060. this._cachedWAng = this.wAng;
  31061. if (!this._cachedTextureMatrix) {
  31062. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31063. this._rowGenerationMatrix = new BABYLON.Matrix();
  31064. this._t0 = BABYLON.Vector3.Zero();
  31065. this._t1 = BABYLON.Vector3.Zero();
  31066. this._t2 = BABYLON.Vector3.Zero();
  31067. }
  31068. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31069. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31070. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31071. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31072. this._t1.subtractInPlace(this._t0);
  31073. this._t2.subtractInPlace(this._t0);
  31074. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31075. this._cachedTextureMatrix.m[0] = this._t1.x;
  31076. this._cachedTextureMatrix.m[1] = this._t1.y;
  31077. this._cachedTextureMatrix.m[2] = this._t1.z;
  31078. this._cachedTextureMatrix.m[4] = this._t2.x;
  31079. this._cachedTextureMatrix.m[5] = this._t2.y;
  31080. this._cachedTextureMatrix.m[6] = this._t2.z;
  31081. this._cachedTextureMatrix.m[8] = this._t0.x;
  31082. this._cachedTextureMatrix.m[9] = this._t0.y;
  31083. this._cachedTextureMatrix.m[10] = this._t0.z;
  31084. var scene = this.getScene();
  31085. if (!scene) {
  31086. return this._cachedTextureMatrix;
  31087. }
  31088. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31089. return mat.hasTexture(_this);
  31090. });
  31091. return this._cachedTextureMatrix;
  31092. };
  31093. Texture.prototype.getReflectionTextureMatrix = function () {
  31094. var _this = this;
  31095. var scene = this.getScene();
  31096. if (!scene) {
  31097. return this._cachedTextureMatrix;
  31098. }
  31099. if (this.uOffset === this._cachedUOffset &&
  31100. this.vOffset === this._cachedVOffset &&
  31101. this.uScale === this._cachedUScale &&
  31102. this.vScale === this._cachedVScale &&
  31103. this.coordinatesMode === this._cachedCoordinatesMode) {
  31104. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31105. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31106. return this._cachedTextureMatrix;
  31107. }
  31108. }
  31109. else {
  31110. return this._cachedTextureMatrix;
  31111. }
  31112. }
  31113. if (!this._cachedTextureMatrix) {
  31114. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31115. }
  31116. if (!this._projectionModeMatrix) {
  31117. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31118. }
  31119. this._cachedUOffset = this.uOffset;
  31120. this._cachedVOffset = this.vOffset;
  31121. this._cachedUScale = this.uScale;
  31122. this._cachedVScale = this.vScale;
  31123. this._cachedCoordinatesMode = this.coordinatesMode;
  31124. switch (this.coordinatesMode) {
  31125. case Texture.PLANAR_MODE:
  31126. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31127. this._cachedTextureMatrix[0] = this.uScale;
  31128. this._cachedTextureMatrix[5] = this.vScale;
  31129. this._cachedTextureMatrix[12] = this.uOffset;
  31130. this._cachedTextureMatrix[13] = this.vOffset;
  31131. break;
  31132. case Texture.PROJECTION_MODE:
  31133. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31134. this._projectionModeMatrix.m[0] = 0.5;
  31135. this._projectionModeMatrix.m[5] = -0.5;
  31136. this._projectionModeMatrix.m[10] = 0.0;
  31137. this._projectionModeMatrix.m[12] = 0.5;
  31138. this._projectionModeMatrix.m[13] = 0.5;
  31139. this._projectionModeMatrix.m[14] = 1.0;
  31140. this._projectionModeMatrix.m[15] = 1.0;
  31141. var projectionMatrix = scene.getProjectionMatrix();
  31142. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31143. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31144. break;
  31145. default:
  31146. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31147. break;
  31148. }
  31149. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31150. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31151. });
  31152. return this._cachedTextureMatrix;
  31153. };
  31154. Texture.prototype.clone = function () {
  31155. var _this = this;
  31156. return BABYLON.SerializationHelper.Clone(function () {
  31157. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31158. }, this);
  31159. };
  31160. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31161. get: function () {
  31162. if (!this._onLoadObservable) {
  31163. this._onLoadObservable = new BABYLON.Observable();
  31164. }
  31165. return this._onLoadObservable;
  31166. },
  31167. enumerable: true,
  31168. configurable: true
  31169. });
  31170. Texture.prototype.serialize = function () {
  31171. var serializationObject = _super.prototype.serialize.call(this);
  31172. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31173. serializationObject.base64String = this._buffer;
  31174. serializationObject.name = serializationObject.name.replace("data:", "");
  31175. }
  31176. serializationObject.invertY = this._invertY;
  31177. serializationObject.samplingMode = this.samplingMode;
  31178. return serializationObject;
  31179. };
  31180. Texture.prototype.getClassName = function () {
  31181. return "Texture";
  31182. };
  31183. Texture.prototype.dispose = function () {
  31184. _super.prototype.dispose.call(this);
  31185. if (this._onLoadObservable) {
  31186. this._onLoadObservable.clear();
  31187. this._onLoadObservable = null;
  31188. }
  31189. this._delayedOnLoad = null;
  31190. this._delayedOnError = null;
  31191. };
  31192. // Statics
  31193. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31194. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31195. if (onLoad === void 0) { onLoad = null; }
  31196. if (onError === void 0) { onError = null; }
  31197. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31198. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31199. };
  31200. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31201. if (parsedTexture.customType) {
  31202. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31203. // Update Sampling Mode
  31204. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31205. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31206. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31207. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31208. }
  31209. }
  31210. return parsedCustomTexture;
  31211. }
  31212. if (parsedTexture.isCube) {
  31213. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31214. }
  31215. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31216. return null;
  31217. }
  31218. var texture = BABYLON.SerializationHelper.Parse(function () {
  31219. var generateMipMaps = true;
  31220. if (parsedTexture.noMipmap) {
  31221. generateMipMaps = false;
  31222. }
  31223. if (parsedTexture.mirrorPlane) {
  31224. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31225. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31226. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31227. return mirrorTexture;
  31228. }
  31229. else if (parsedTexture.isRenderTarget) {
  31230. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31231. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31232. return renderTargetTexture;
  31233. }
  31234. else {
  31235. var texture;
  31236. if (parsedTexture.base64String) {
  31237. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31238. }
  31239. else {
  31240. var url = rootUrl + parsedTexture.name;
  31241. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31242. url = parsedTexture.url;
  31243. }
  31244. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31245. }
  31246. return texture;
  31247. }
  31248. }, parsedTexture, scene);
  31249. // Update Sampling Mode
  31250. if (parsedTexture.samplingMode) {
  31251. var sampling = parsedTexture.samplingMode;
  31252. if (texture._samplingMode !== sampling) {
  31253. texture.updateSamplingMode(sampling);
  31254. }
  31255. }
  31256. // Animations
  31257. if (parsedTexture.animations) {
  31258. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31259. var parsedAnimation = parsedTexture.animations[animationIndex];
  31260. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31261. }
  31262. }
  31263. return texture;
  31264. };
  31265. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31266. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31267. if (noMipmap === void 0) { noMipmap = false; }
  31268. if (invertY === void 0) { invertY = true; }
  31269. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31270. if (onLoad === void 0) { onLoad = null; }
  31271. if (onError === void 0) { onError = null; }
  31272. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31273. if (name.substr(0, 5) !== "data:") {
  31274. name = "data:" + name;
  31275. }
  31276. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31277. };
  31278. // Constants
  31279. Texture.NEAREST_SAMPLINGMODE = 1;
  31280. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31281. Texture.BILINEAR_SAMPLINGMODE = 2;
  31282. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31283. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31284. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31285. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31286. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31287. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31288. Texture.NEAREST_LINEAR = 7;
  31289. Texture.NEAREST_NEAREST = 8;
  31290. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31291. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31292. Texture.LINEAR_LINEAR = 11;
  31293. Texture.LINEAR_NEAREST = 12;
  31294. Texture.EXPLICIT_MODE = 0;
  31295. Texture.SPHERICAL_MODE = 1;
  31296. Texture.PLANAR_MODE = 2;
  31297. Texture.CUBIC_MODE = 3;
  31298. Texture.PROJECTION_MODE = 4;
  31299. Texture.SKYBOX_MODE = 5;
  31300. Texture.INVCUBIC_MODE = 6;
  31301. Texture.EQUIRECTANGULAR_MODE = 7;
  31302. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31303. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31304. Texture.CLAMP_ADDRESSMODE = 0;
  31305. Texture.WRAP_ADDRESSMODE = 1;
  31306. Texture.MIRROR_ADDRESSMODE = 2;
  31307. /**
  31308. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  31309. */
  31310. Texture.UseSerializedUrlIfAny = false;
  31311. __decorate([
  31312. BABYLON.serialize()
  31313. ], Texture.prototype, "url", void 0);
  31314. __decorate([
  31315. BABYLON.serialize()
  31316. ], Texture.prototype, "uOffset", void 0);
  31317. __decorate([
  31318. BABYLON.serialize()
  31319. ], Texture.prototype, "vOffset", void 0);
  31320. __decorate([
  31321. BABYLON.serialize()
  31322. ], Texture.prototype, "uScale", void 0);
  31323. __decorate([
  31324. BABYLON.serialize()
  31325. ], Texture.prototype, "vScale", void 0);
  31326. __decorate([
  31327. BABYLON.serialize()
  31328. ], Texture.prototype, "uAng", void 0);
  31329. __decorate([
  31330. BABYLON.serialize()
  31331. ], Texture.prototype, "vAng", void 0);
  31332. __decorate([
  31333. BABYLON.serialize()
  31334. ], Texture.prototype, "wAng", void 0);
  31335. __decorate([
  31336. BABYLON.serialize()
  31337. ], Texture.prototype, "uRotationCenter", void 0);
  31338. __decorate([
  31339. BABYLON.serialize()
  31340. ], Texture.prototype, "vRotationCenter", void 0);
  31341. __decorate([
  31342. BABYLON.serialize()
  31343. ], Texture.prototype, "wRotationCenter", void 0);
  31344. __decorate([
  31345. BABYLON.serialize()
  31346. ], Texture.prototype, "isBlocking", null);
  31347. return Texture;
  31348. }(BABYLON.BaseTexture));
  31349. BABYLON.Texture = Texture;
  31350. })(BABYLON || (BABYLON = {}));
  31351. //# sourceMappingURL=babylon.texture.js.map
  31352. var BABYLON;
  31353. (function (BABYLON) {
  31354. /**
  31355. * @hidden
  31356. **/
  31357. var _InstancesBatch = /** @class */ (function () {
  31358. function _InstancesBatch() {
  31359. this.mustReturn = false;
  31360. this.visibleInstances = new Array();
  31361. this.renderSelf = new Array();
  31362. }
  31363. return _InstancesBatch;
  31364. }());
  31365. BABYLON._InstancesBatch = _InstancesBatch;
  31366. var Mesh = /** @class */ (function (_super) {
  31367. __extends(Mesh, _super);
  31368. /**
  31369. * @constructor
  31370. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31371. * @param {Scene} scene The scene to add this mesh to.
  31372. * @param {Node} parent The parent of this mesh, if it has one
  31373. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31374. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31375. * When false, achieved by calling a clone(), also passing False.
  31376. * This will make creation of children, recursive.
  31377. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31378. */
  31379. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31380. if (scene === void 0) { scene = null; }
  31381. if (parent === void 0) { parent = null; }
  31382. if (source === void 0) { source = null; }
  31383. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31384. var _this = _super.call(this, name, scene) || this;
  31385. // Events
  31386. /**
  31387. * An event triggered before rendering the mesh
  31388. */
  31389. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31390. /**
  31391. * An event triggered after rendering the mesh
  31392. */
  31393. _this.onAfterRenderObservable = new BABYLON.Observable();
  31394. /**
  31395. * An event triggered before drawing the mesh
  31396. */
  31397. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31398. // Members
  31399. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31400. _this.instances = new Array();
  31401. _this._LODLevels = new Array();
  31402. _this._visibleInstances = {};
  31403. _this._renderIdForInstances = new Array();
  31404. _this._batchCache = new _InstancesBatch();
  31405. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31406. // Use by builder only to know what orientation were the mesh build in.
  31407. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31408. _this.overrideMaterialSideOrientation = null;
  31409. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31410. // Will be used to save a source mesh reference, If any
  31411. _this._source = null;
  31412. scene = _this.getScene();
  31413. if (source) {
  31414. // Geometry
  31415. if (source._geometry) {
  31416. source._geometry.applyToMesh(_this);
  31417. }
  31418. // Deep copy
  31419. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31420. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31421. // Source mesh
  31422. _this._source = source;
  31423. // Metadata
  31424. if (source.metadata && source.metadata.clone) {
  31425. _this.metadata = source.metadata.clone();
  31426. }
  31427. else {
  31428. _this.metadata = source.metadata;
  31429. }
  31430. // Tags
  31431. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31432. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31433. }
  31434. // Parent
  31435. _this.parent = source.parent;
  31436. // Pivot
  31437. _this.setPivotMatrix(source.getPivotMatrix());
  31438. _this.id = name + "." + source.id;
  31439. // Material
  31440. _this.material = source.material;
  31441. var index;
  31442. if (!doNotCloneChildren) {
  31443. // Children
  31444. var directDescendants = source.getDescendants(true);
  31445. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31446. var child = directDescendants[index_1];
  31447. if (child.clone) {
  31448. child.clone(name + "." + child.name, _this);
  31449. }
  31450. }
  31451. }
  31452. // Physics clone
  31453. var physicsEngine = _this.getScene().getPhysicsEngine();
  31454. if (clonePhysicsImpostor && physicsEngine) {
  31455. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31456. if (impostor) {
  31457. _this.physicsImpostor = impostor.clone(_this);
  31458. }
  31459. }
  31460. // Particles
  31461. for (index = 0; index < scene.particleSystems.length; index++) {
  31462. var system = scene.particleSystems[index];
  31463. if (system.emitter === source) {
  31464. system.clone(system.name, _this);
  31465. }
  31466. }
  31467. _this.refreshBoundingInfo();
  31468. _this.computeWorldMatrix(true);
  31469. }
  31470. // Parent
  31471. if (parent !== null) {
  31472. _this.parent = parent;
  31473. }
  31474. return _this;
  31475. }
  31476. Object.defineProperty(Mesh, "FRONTSIDE", {
  31477. /**
  31478. * Mesh side orientation : usually the external or front surface
  31479. */
  31480. get: function () {
  31481. return Mesh._FRONTSIDE;
  31482. },
  31483. enumerable: true,
  31484. configurable: true
  31485. });
  31486. Object.defineProperty(Mesh, "BACKSIDE", {
  31487. /**
  31488. * Mesh side orientation : usually the internal or back surface
  31489. */
  31490. get: function () {
  31491. return Mesh._BACKSIDE;
  31492. },
  31493. enumerable: true,
  31494. configurable: true
  31495. });
  31496. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31497. /**
  31498. * Mesh side orientation : both internal and external or front and back surfaces
  31499. */
  31500. get: function () {
  31501. return Mesh._DOUBLESIDE;
  31502. },
  31503. enumerable: true,
  31504. configurable: true
  31505. });
  31506. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31507. /**
  31508. * Mesh side orientation : by default, `FRONTSIDE`
  31509. */
  31510. get: function () {
  31511. return Mesh._DEFAULTSIDE;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. Object.defineProperty(Mesh, "NO_CAP", {
  31517. /**
  31518. * Mesh cap setting : no cap
  31519. */
  31520. get: function () {
  31521. return Mesh._NO_CAP;
  31522. },
  31523. enumerable: true,
  31524. configurable: true
  31525. });
  31526. Object.defineProperty(Mesh, "CAP_START", {
  31527. /**
  31528. * Mesh cap setting : one cap at the beginning of the mesh
  31529. */
  31530. get: function () {
  31531. return Mesh._CAP_START;
  31532. },
  31533. enumerable: true,
  31534. configurable: true
  31535. });
  31536. Object.defineProperty(Mesh, "CAP_END", {
  31537. /**
  31538. * Mesh cap setting : one cap at the end of the mesh
  31539. */
  31540. get: function () {
  31541. return Mesh._CAP_END;
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. Object.defineProperty(Mesh, "CAP_ALL", {
  31547. /**
  31548. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31549. */
  31550. get: function () {
  31551. return Mesh._CAP_ALL;
  31552. },
  31553. enumerable: true,
  31554. configurable: true
  31555. });
  31556. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31557. set: function (callback) {
  31558. if (this._onBeforeDrawObserver) {
  31559. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31560. }
  31561. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31562. },
  31563. enumerable: true,
  31564. configurable: true
  31565. });
  31566. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31567. get: function () {
  31568. return this._morphTargetManager;
  31569. },
  31570. set: function (value) {
  31571. if (this._morphTargetManager === value) {
  31572. return;
  31573. }
  31574. this._morphTargetManager = value;
  31575. this._syncGeometryWithMorphTargetManager();
  31576. },
  31577. enumerable: true,
  31578. configurable: true
  31579. });
  31580. Object.defineProperty(Mesh.prototype, "source", {
  31581. get: function () {
  31582. return this._source;
  31583. },
  31584. enumerable: true,
  31585. configurable: true
  31586. });
  31587. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31588. get: function () {
  31589. return this._unIndexed;
  31590. },
  31591. set: function (value) {
  31592. if (this._unIndexed !== value) {
  31593. this._unIndexed = value;
  31594. this._markSubMeshesAsAttributesDirty();
  31595. }
  31596. },
  31597. enumerable: true,
  31598. configurable: true
  31599. });
  31600. // Methods
  31601. /**
  31602. * Returns the string "Mesh".
  31603. */
  31604. Mesh.prototype.getClassName = function () {
  31605. return "Mesh";
  31606. };
  31607. /**
  31608. * Returns a string.
  31609. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31610. */
  31611. Mesh.prototype.toString = function (fullDetails) {
  31612. var ret = _super.prototype.toString.call(this, fullDetails);
  31613. ret += ", n vertices: " + this.getTotalVertices();
  31614. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31615. if (this.animations) {
  31616. for (var i = 0; i < this.animations.length; i++) {
  31617. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31618. }
  31619. }
  31620. if (fullDetails) {
  31621. if (this._geometry) {
  31622. var ib = this.getIndices();
  31623. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31624. if (vb && ib) {
  31625. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31626. }
  31627. }
  31628. else {
  31629. ret += ", flat shading: UNKNOWN";
  31630. }
  31631. }
  31632. return ret;
  31633. };
  31634. Mesh.prototype._unBindEffect = function () {
  31635. _super.prototype._unBindEffect.call(this);
  31636. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31637. var instance = _a[_i];
  31638. instance._unBindEffect();
  31639. }
  31640. };
  31641. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31642. /**
  31643. * True if the mesh has some Levels Of Details (LOD).
  31644. * Returns a boolean.
  31645. */
  31646. get: function () {
  31647. return this._LODLevels.length > 0;
  31648. },
  31649. enumerable: true,
  31650. configurable: true
  31651. });
  31652. /**
  31653. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31654. * @returns an array of {BABYLON.MeshLODLevel}
  31655. */
  31656. Mesh.prototype.getLODLevels = function () {
  31657. return this._LODLevels;
  31658. };
  31659. Mesh.prototype._sortLODLevels = function () {
  31660. this._LODLevels.sort(function (a, b) {
  31661. if (a.distance < b.distance) {
  31662. return 1;
  31663. }
  31664. if (a.distance > b.distance) {
  31665. return -1;
  31666. }
  31667. return 0;
  31668. });
  31669. };
  31670. /**
  31671. * Add a mesh as LOD level triggered at the given distance.
  31672. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31673. * @param distance The distance from the center of the object to show this level
  31674. * @param mesh The mesh to be added as LOD level (can be null)
  31675. * @return This mesh (for chaining)
  31676. */
  31677. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31678. if (mesh && mesh._masterMesh) {
  31679. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31680. return this;
  31681. }
  31682. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31683. this._LODLevels.push(level);
  31684. if (mesh) {
  31685. mesh._masterMesh = this;
  31686. }
  31687. this._sortLODLevels();
  31688. return this;
  31689. };
  31690. /**
  31691. * Returns the LOD level mesh at the passed distance or null if not found.
  31692. * It is related to the method `addLODLevel(distance, mesh)`.
  31693. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31694. * Returns an object Mesh or `null`.
  31695. */
  31696. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31697. for (var index = 0; index < this._LODLevels.length; index++) {
  31698. var level = this._LODLevels[index];
  31699. if (level.distance === distance) {
  31700. return level.mesh;
  31701. }
  31702. }
  31703. return null;
  31704. };
  31705. /**
  31706. * Remove a mesh from the LOD array
  31707. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31708. * @param {Mesh} mesh The mesh to be removed.
  31709. * @return {Mesh} This mesh (for chaining)
  31710. */
  31711. Mesh.prototype.removeLODLevel = function (mesh) {
  31712. for (var index = 0; index < this._LODLevels.length; index++) {
  31713. if (this._LODLevels[index].mesh === mesh) {
  31714. this._LODLevels.splice(index, 1);
  31715. if (mesh) {
  31716. mesh._masterMesh = null;
  31717. }
  31718. }
  31719. }
  31720. this._sortLODLevels();
  31721. return this;
  31722. };
  31723. /**
  31724. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31725. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31726. */
  31727. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31728. if (!this._LODLevels || this._LODLevels.length === 0) {
  31729. return this;
  31730. }
  31731. var bSphere;
  31732. if (boundingSphere) {
  31733. bSphere = boundingSphere;
  31734. }
  31735. else {
  31736. var boundingInfo = this.getBoundingInfo();
  31737. bSphere = boundingInfo.boundingSphere;
  31738. }
  31739. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31740. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31741. if (this.onLODLevelSelection) {
  31742. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31743. }
  31744. return this;
  31745. }
  31746. for (var index = 0; index < this._LODLevels.length; index++) {
  31747. var level = this._LODLevels[index];
  31748. if (level.distance < distanceToCamera) {
  31749. if (level.mesh) {
  31750. level.mesh._preActivate();
  31751. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31752. }
  31753. if (this.onLODLevelSelection) {
  31754. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31755. }
  31756. return level.mesh;
  31757. }
  31758. }
  31759. if (this.onLODLevelSelection) {
  31760. this.onLODLevelSelection(distanceToCamera, this, this);
  31761. }
  31762. return this;
  31763. };
  31764. Object.defineProperty(Mesh.prototype, "geometry", {
  31765. /**
  31766. * Returns the mesh internal Geometry object.
  31767. */
  31768. get: function () {
  31769. return this._geometry;
  31770. },
  31771. enumerable: true,
  31772. configurable: true
  31773. });
  31774. /**
  31775. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31776. */
  31777. Mesh.prototype.getTotalVertices = function () {
  31778. if (this._geometry === null || this._geometry === undefined) {
  31779. return 0;
  31780. }
  31781. return this._geometry.getTotalVertices();
  31782. };
  31783. /**
  31784. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31785. * 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.
  31786. * You can force the copy with forceCopy === true
  31787. * Returns null if the mesh has no geometry or no vertex buffer.
  31788. * Possible `kind` values :
  31789. * - BABYLON.VertexBuffer.PositionKind
  31790. * - BABYLON.VertexBuffer.UVKind
  31791. * - BABYLON.VertexBuffer.UV2Kind
  31792. * - BABYLON.VertexBuffer.UV3Kind
  31793. * - BABYLON.VertexBuffer.UV4Kind
  31794. * - BABYLON.VertexBuffer.UV5Kind
  31795. * - BABYLON.VertexBuffer.UV6Kind
  31796. * - BABYLON.VertexBuffer.ColorKind
  31797. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31798. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31799. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31800. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31801. */
  31802. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31803. if (!this._geometry) {
  31804. return null;
  31805. }
  31806. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31807. };
  31808. /**
  31809. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31810. * Returns `null` if the mesh has no geometry.
  31811. * Possible `kind` values :
  31812. * - BABYLON.VertexBuffer.PositionKind
  31813. * - BABYLON.VertexBuffer.UVKind
  31814. * - BABYLON.VertexBuffer.UV2Kind
  31815. * - BABYLON.VertexBuffer.UV3Kind
  31816. * - BABYLON.VertexBuffer.UV4Kind
  31817. * - BABYLON.VertexBuffer.UV5Kind
  31818. * - BABYLON.VertexBuffer.UV6Kind
  31819. * - BABYLON.VertexBuffer.ColorKind
  31820. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31821. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31822. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31823. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31824. */
  31825. Mesh.prototype.getVertexBuffer = function (kind) {
  31826. if (!this._geometry) {
  31827. return null;
  31828. }
  31829. return this._geometry.getVertexBuffer(kind);
  31830. };
  31831. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31832. if (!this._geometry) {
  31833. if (this._delayInfo) {
  31834. return this._delayInfo.indexOf(kind) !== -1;
  31835. }
  31836. return false;
  31837. }
  31838. return this._geometry.isVerticesDataPresent(kind);
  31839. };
  31840. /**
  31841. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31842. * Possible `kind` values :
  31843. * - BABYLON.VertexBuffer.PositionKind
  31844. * - BABYLON.VertexBuffer.UVKind
  31845. * - BABYLON.VertexBuffer.UV2Kind
  31846. * - BABYLON.VertexBuffer.UV3Kind
  31847. * - BABYLON.VertexBuffer.UV4Kind
  31848. * - BABYLON.VertexBuffer.UV5Kind
  31849. * - BABYLON.VertexBuffer.UV6Kind
  31850. * - BABYLON.VertexBuffer.ColorKind
  31851. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31852. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31853. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31854. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31855. */
  31856. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31857. if (!this._geometry) {
  31858. if (this._delayInfo) {
  31859. return this._delayInfo.indexOf(kind) !== -1;
  31860. }
  31861. return false;
  31862. }
  31863. return this._geometry.isVertexBufferUpdatable(kind);
  31864. };
  31865. /**
  31866. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31867. * Possible `kind` values :
  31868. * - BABYLON.VertexBuffer.PositionKind
  31869. * - BABYLON.VertexBuffer.UVKind
  31870. * - BABYLON.VertexBuffer.UV2Kind
  31871. * - BABYLON.VertexBuffer.UV3Kind
  31872. * - BABYLON.VertexBuffer.UV4Kind
  31873. * - BABYLON.VertexBuffer.UV5Kind
  31874. * - BABYLON.VertexBuffer.UV6Kind
  31875. * - BABYLON.VertexBuffer.ColorKind
  31876. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31877. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31878. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31879. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31880. */
  31881. Mesh.prototype.getVerticesDataKinds = function () {
  31882. if (!this._geometry) {
  31883. var result = new Array();
  31884. if (this._delayInfo) {
  31885. this._delayInfo.forEach(function (kind, index, array) {
  31886. result.push(kind);
  31887. });
  31888. }
  31889. return result;
  31890. }
  31891. return this._geometry.getVerticesDataKinds();
  31892. };
  31893. /**
  31894. * Returns a positive integer : the total number of indices in this mesh geometry.
  31895. * Returns zero if the mesh has no geometry.
  31896. */
  31897. Mesh.prototype.getTotalIndices = function () {
  31898. if (!this._geometry) {
  31899. return 0;
  31900. }
  31901. return this._geometry.getTotalIndices();
  31902. };
  31903. /**
  31904. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31905. * 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.
  31906. * Returns an empty array if the mesh has no geometry.
  31907. */
  31908. Mesh.prototype.getIndices = function (copyWhenShared) {
  31909. if (!this._geometry) {
  31910. return [];
  31911. }
  31912. return this._geometry.getIndices(copyWhenShared);
  31913. };
  31914. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31915. get: function () {
  31916. return this._masterMesh !== null && this._masterMesh !== undefined;
  31917. },
  31918. enumerable: true,
  31919. configurable: true
  31920. });
  31921. /**
  31922. * Determine if the current mesh is ready to be rendered
  31923. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31924. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31925. * @returns true if all associated assets are ready (material, textures, shaders)
  31926. */
  31927. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31928. if (completeCheck === void 0) { completeCheck = false; }
  31929. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31930. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31931. return false;
  31932. }
  31933. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31934. return false;
  31935. }
  31936. if (!this.subMeshes || this.subMeshes.length === 0) {
  31937. return true;
  31938. }
  31939. if (!completeCheck) {
  31940. return true;
  31941. }
  31942. var engine = this.getEngine();
  31943. var scene = this.getScene();
  31944. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31945. this.computeWorldMatrix();
  31946. var mat = this.material || scene.defaultMaterial;
  31947. if (mat) {
  31948. if (mat.storeEffectOnSubMeshes) {
  31949. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31950. var subMesh = _a[_i];
  31951. var effectiveMaterial = subMesh.getMaterial();
  31952. if (effectiveMaterial) {
  31953. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31954. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31955. return false;
  31956. }
  31957. }
  31958. else {
  31959. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31960. return false;
  31961. }
  31962. }
  31963. }
  31964. }
  31965. }
  31966. else {
  31967. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31968. return false;
  31969. }
  31970. }
  31971. }
  31972. // Shadows
  31973. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31974. var light = _c[_b];
  31975. var generator = light.getShadowGenerator();
  31976. if (generator) {
  31977. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31978. var subMesh = _e[_d];
  31979. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31980. return false;
  31981. }
  31982. }
  31983. }
  31984. }
  31985. // LOD
  31986. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31987. var lod = _g[_f];
  31988. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31989. return false;
  31990. }
  31991. }
  31992. return true;
  31993. };
  31994. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31995. /**
  31996. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31997. * This property is pertinent only for updatable parametric shapes.
  31998. */
  31999. get: function () {
  32000. return this._areNormalsFrozen;
  32001. },
  32002. enumerable: true,
  32003. configurable: true
  32004. });
  32005. /**
  32006. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32007. * It has no effect at all on other shapes.
  32008. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32009. * Returns the Mesh.
  32010. */
  32011. Mesh.prototype.freezeNormals = function () {
  32012. this._areNormalsFrozen = true;
  32013. return this;
  32014. };
  32015. /**
  32016. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32017. * It has no effect at all on other shapes.
  32018. * It reactivates the mesh normals computation if it was previously frozen.
  32019. * Returns the Mesh.
  32020. */
  32021. Mesh.prototype.unfreezeNormals = function () {
  32022. this._areNormalsFrozen = false;
  32023. return this;
  32024. };
  32025. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32026. /**
  32027. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32028. */
  32029. set: function (count) {
  32030. this._overridenInstanceCount = count;
  32031. },
  32032. enumerable: true,
  32033. configurable: true
  32034. });
  32035. // Methods
  32036. Mesh.prototype._preActivate = function () {
  32037. var sceneRenderId = this.getScene().getRenderId();
  32038. if (this._preActivateId === sceneRenderId) {
  32039. return this;
  32040. }
  32041. this._preActivateId = sceneRenderId;
  32042. this._visibleInstances = null;
  32043. return this;
  32044. };
  32045. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32046. if (this._visibleInstances) {
  32047. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32048. }
  32049. return this;
  32050. };
  32051. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32052. if (!this._visibleInstances) {
  32053. this._visibleInstances = {};
  32054. this._visibleInstances.defaultRenderId = renderId;
  32055. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32056. }
  32057. if (!this._visibleInstances[renderId]) {
  32058. this._visibleInstances[renderId] = new Array();
  32059. }
  32060. this._visibleInstances[renderId].push(instance);
  32061. return this;
  32062. };
  32063. /**
  32064. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32065. * This means the mesh underlying bounding box and sphere are recomputed.
  32066. * Returns the Mesh.
  32067. */
  32068. Mesh.prototype.refreshBoundingInfo = function () {
  32069. return this._refreshBoundingInfo(false);
  32070. };
  32071. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32072. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32073. return this;
  32074. }
  32075. var data = this._getPositionData(applySkeleton);
  32076. if (data) {
  32077. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32078. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32079. }
  32080. if (this.subMeshes) {
  32081. for (var index = 0; index < this.subMeshes.length; index++) {
  32082. this.subMeshes[index].refreshBoundingInfo();
  32083. }
  32084. }
  32085. this._updateBoundingInfo();
  32086. return this;
  32087. };
  32088. Mesh.prototype._getPositionData = function (applySkeleton) {
  32089. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32090. if (data && applySkeleton && this.skeleton) {
  32091. data = BABYLON.Tools.Slice(data);
  32092. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32093. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32094. if (matricesWeightsData && matricesIndicesData) {
  32095. var needExtras = this.numBoneInfluencers > 4;
  32096. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32097. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32098. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32099. var tempVector = BABYLON.Tmp.Vector3[0];
  32100. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32101. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32102. var matWeightIdx = 0;
  32103. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32104. finalMatrix.reset();
  32105. var inf;
  32106. var weight;
  32107. for (inf = 0; inf < 4; inf++) {
  32108. weight = matricesWeightsData[matWeightIdx + inf];
  32109. if (weight <= 0)
  32110. break;
  32111. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32112. finalMatrix.addToSelf(tempMatrix);
  32113. }
  32114. if (needExtras) {
  32115. for (inf = 0; inf < 4; inf++) {
  32116. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32117. if (weight <= 0)
  32118. break;
  32119. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32120. finalMatrix.addToSelf(tempMatrix);
  32121. }
  32122. }
  32123. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32124. tempVector.toArray(data, index);
  32125. }
  32126. }
  32127. }
  32128. return data;
  32129. };
  32130. Mesh.prototype._createGlobalSubMesh = function (force) {
  32131. var totalVertices = this.getTotalVertices();
  32132. if (!totalVertices || !this.getIndices()) {
  32133. return null;
  32134. }
  32135. // Check if we need to recreate the submeshes
  32136. if (this.subMeshes && this.subMeshes.length > 0) {
  32137. var ib = this.getIndices();
  32138. if (!ib) {
  32139. return null;
  32140. }
  32141. var totalIndices = ib.length;
  32142. var needToRecreate = false;
  32143. if (force) {
  32144. needToRecreate = true;
  32145. }
  32146. else {
  32147. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32148. var submesh = _a[_i];
  32149. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32150. needToRecreate = true;
  32151. break;
  32152. }
  32153. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32154. needToRecreate = true;
  32155. break;
  32156. }
  32157. }
  32158. }
  32159. if (!needToRecreate) {
  32160. return this.subMeshes[0];
  32161. }
  32162. }
  32163. this.releaseSubMeshes();
  32164. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32165. };
  32166. Mesh.prototype.subdivide = function (count) {
  32167. if (count < 1) {
  32168. return;
  32169. }
  32170. var totalIndices = this.getTotalIndices();
  32171. var subdivisionSize = (totalIndices / count) | 0;
  32172. var offset = 0;
  32173. // Ensure that subdivisionSize is a multiple of 3
  32174. while (subdivisionSize % 3 !== 0) {
  32175. subdivisionSize++;
  32176. }
  32177. this.releaseSubMeshes();
  32178. for (var index = 0; index < count; index++) {
  32179. if (offset >= totalIndices) {
  32180. break;
  32181. }
  32182. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32183. offset += subdivisionSize;
  32184. }
  32185. this.synchronizeInstances();
  32186. };
  32187. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32188. if (updatable === void 0) { updatable = false; }
  32189. if (!this._geometry) {
  32190. var vertexData = new BABYLON.VertexData();
  32191. vertexData.set(data, kind);
  32192. var scene = this.getScene();
  32193. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32194. }
  32195. else {
  32196. this._geometry.setVerticesData(kind, data, updatable, stride);
  32197. }
  32198. return this;
  32199. };
  32200. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32201. if (updatable === void 0) { updatable = true; }
  32202. var vb = this.getVertexBuffer(kind);
  32203. if (!vb || vb.isUpdatable() === updatable) {
  32204. return;
  32205. }
  32206. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32207. };
  32208. /**
  32209. * Sets the mesh VertexBuffer.
  32210. * Returns the Mesh.
  32211. */
  32212. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32213. if (!this._geometry) {
  32214. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32215. }
  32216. this._geometry.setVerticesBuffer(buffer);
  32217. return this;
  32218. };
  32219. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32220. if (!this._geometry) {
  32221. return this;
  32222. }
  32223. if (!makeItUnique) {
  32224. this._geometry.updateVerticesData(kind, data, updateExtends);
  32225. }
  32226. else {
  32227. this.makeGeometryUnique();
  32228. this.updateVerticesData(kind, data, updateExtends, false);
  32229. }
  32230. return this;
  32231. };
  32232. /**
  32233. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32234. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32235. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32236. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32237. * Returns the Mesh.
  32238. */
  32239. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32240. if (computeNormals === void 0) { computeNormals = true; }
  32241. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32242. if (!positions) {
  32243. return this;
  32244. }
  32245. positionFunction(positions);
  32246. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32247. if (computeNormals) {
  32248. var indices = this.getIndices();
  32249. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32250. if (!normals) {
  32251. return this;
  32252. }
  32253. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32254. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32255. }
  32256. return this;
  32257. };
  32258. /**
  32259. * Creates a un-shared specific occurence of the geometry for the mesh.
  32260. * Returns the Mesh.
  32261. */
  32262. Mesh.prototype.makeGeometryUnique = function () {
  32263. if (!this._geometry) {
  32264. return this;
  32265. }
  32266. var oldGeometry = this._geometry;
  32267. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32268. oldGeometry.releaseForMesh(this, true);
  32269. geometry.applyToMesh(this);
  32270. return this;
  32271. };
  32272. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32273. if (totalVertices === void 0) { totalVertices = null; }
  32274. if (updatable === void 0) { updatable = false; }
  32275. if (!this._geometry) {
  32276. var vertexData = new BABYLON.VertexData();
  32277. vertexData.indices = indices;
  32278. var scene = this.getScene();
  32279. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32280. }
  32281. else {
  32282. this._geometry.setIndices(indices, totalVertices, updatable);
  32283. }
  32284. return this;
  32285. };
  32286. /**
  32287. * Update the current index buffer
  32288. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32289. * Returns the Mesh.
  32290. */
  32291. Mesh.prototype.updateIndices = function (indices, offset) {
  32292. if (!this._geometry) {
  32293. return this;
  32294. }
  32295. this._geometry.updateIndices(indices, offset);
  32296. return this;
  32297. };
  32298. /**
  32299. * Invert the geometry to move from a right handed system to a left handed one.
  32300. * Returns the Mesh.
  32301. */
  32302. Mesh.prototype.toLeftHanded = function () {
  32303. if (!this._geometry) {
  32304. return this;
  32305. }
  32306. this._geometry.toLeftHanded();
  32307. return this;
  32308. };
  32309. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32310. if (!this._geometry) {
  32311. return this;
  32312. }
  32313. var engine = this.getScene().getEngine();
  32314. // Wireframe
  32315. var indexToBind;
  32316. if (this._unIndexed) {
  32317. indexToBind = null;
  32318. }
  32319. else {
  32320. switch (fillMode) {
  32321. case BABYLON.Material.PointFillMode:
  32322. indexToBind = null;
  32323. break;
  32324. case BABYLON.Material.WireFrameFillMode:
  32325. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32326. break;
  32327. default:
  32328. case BABYLON.Material.TriangleFillMode:
  32329. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32330. break;
  32331. }
  32332. }
  32333. // VBOs
  32334. this._geometry._bind(effect, indexToBind);
  32335. return this;
  32336. };
  32337. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32338. if (alternate === void 0) { alternate = false; }
  32339. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32340. return this;
  32341. }
  32342. this.onBeforeDrawObservable.notifyObservers(this);
  32343. var scene = this.getScene();
  32344. var engine = scene.getEngine();
  32345. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32346. // or triangles as points
  32347. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32348. }
  32349. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32350. // Triangles as wireframe
  32351. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32352. }
  32353. else {
  32354. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32355. }
  32356. if (scene._isAlternateRenderingEnabled && !alternate) {
  32357. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32358. if (!effect || !scene.activeCamera) {
  32359. return this;
  32360. }
  32361. scene._switchToAlternateCameraConfiguration(true);
  32362. this._effectiveMaterial.bindView(effect);
  32363. this._effectiveMaterial.bindViewProjection(effect);
  32364. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32365. this._draw(subMesh, fillMode, instancesCount, true);
  32366. engine.setViewport(scene.activeCamera.viewport);
  32367. scene._switchToAlternateCameraConfiguration(false);
  32368. this._effectiveMaterial.bindView(effect);
  32369. this._effectiveMaterial.bindViewProjection(effect);
  32370. }
  32371. return this;
  32372. };
  32373. /**
  32374. * Registers for this mesh a javascript function called just before the rendering process.
  32375. * This function is passed the current mesh.
  32376. * Return the Mesh.
  32377. */
  32378. Mesh.prototype.registerBeforeRender = function (func) {
  32379. this.onBeforeRenderObservable.add(func);
  32380. return this;
  32381. };
  32382. /**
  32383. * Disposes a previously registered javascript function called before the rendering.
  32384. * This function is passed the current mesh.
  32385. * Returns the Mesh.
  32386. */
  32387. Mesh.prototype.unregisterBeforeRender = function (func) {
  32388. this.onBeforeRenderObservable.removeCallback(func);
  32389. return this;
  32390. };
  32391. /**
  32392. * Registers for this mesh a javascript function called just after the rendering is complete.
  32393. * This function is passed the current mesh.
  32394. * Returns the Mesh.
  32395. */
  32396. Mesh.prototype.registerAfterRender = function (func) {
  32397. this.onAfterRenderObservable.add(func);
  32398. return this;
  32399. };
  32400. /**
  32401. * Disposes a previously registered javascript function called after the rendering.
  32402. * This function is passed the current mesh.
  32403. * Return the Mesh.
  32404. */
  32405. Mesh.prototype.unregisterAfterRender = function (func) {
  32406. this.onAfterRenderObservable.removeCallback(func);
  32407. return this;
  32408. };
  32409. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32410. var scene = this.getScene();
  32411. this._batchCache.mustReturn = false;
  32412. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32413. this._batchCache.visibleInstances[subMeshId] = null;
  32414. if (this._visibleInstances) {
  32415. var currentRenderId = scene.getRenderId();
  32416. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32417. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32418. var selfRenderId = this._renderId;
  32419. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32420. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32421. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32422. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32423. }
  32424. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32425. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32426. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32427. this._batchCache.mustReturn = true;
  32428. return this._batchCache;
  32429. }
  32430. if (currentRenderId !== selfRenderId) {
  32431. this._batchCache.renderSelf[subMeshId] = false;
  32432. }
  32433. }
  32434. this._renderIdForInstances[subMeshId] = currentRenderId;
  32435. }
  32436. return this._batchCache;
  32437. };
  32438. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32439. var visibleInstances = batch.visibleInstances[subMesh._id];
  32440. if (!visibleInstances) {
  32441. return this;
  32442. }
  32443. var matricesCount = visibleInstances.length + 1;
  32444. var bufferSize = matricesCount * 16 * 4;
  32445. var currentInstancesBufferSize = this._instancesBufferSize;
  32446. var instancesBuffer = this._instancesBuffer;
  32447. while (this._instancesBufferSize < bufferSize) {
  32448. this._instancesBufferSize *= 2;
  32449. }
  32450. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32451. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32452. }
  32453. var offset = 0;
  32454. var instancesCount = 0;
  32455. var world = this.getWorldMatrix();
  32456. if (batch.renderSelf[subMesh._id]) {
  32457. world.copyToArray(this._instancesData, offset);
  32458. offset += 16;
  32459. instancesCount++;
  32460. }
  32461. if (visibleInstances) {
  32462. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32463. var instance = visibleInstances[instanceIndex];
  32464. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32465. offset += 16;
  32466. instancesCount++;
  32467. }
  32468. }
  32469. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32470. if (instancesBuffer) {
  32471. instancesBuffer.dispose();
  32472. }
  32473. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32474. this._instancesBuffer = instancesBuffer;
  32475. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32476. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32477. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32478. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32479. }
  32480. else {
  32481. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32482. }
  32483. this._bind(subMesh, effect, fillMode);
  32484. this._draw(subMesh, fillMode, instancesCount);
  32485. engine.unbindInstanceAttributes();
  32486. return this;
  32487. };
  32488. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32489. var scene = this.getScene();
  32490. var engine = scene.getEngine();
  32491. if (hardwareInstancedRendering) {
  32492. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32493. }
  32494. else {
  32495. if (batch.renderSelf[subMesh._id]) {
  32496. // Draw
  32497. if (onBeforeDraw) {
  32498. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32499. }
  32500. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32501. }
  32502. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32503. if (visibleInstancesForSubMesh) {
  32504. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32505. var instance = visibleInstancesForSubMesh[instanceIndex];
  32506. // World
  32507. var world = instance.getWorldMatrix();
  32508. if (onBeforeDraw) {
  32509. onBeforeDraw(true, world, effectiveMaterial);
  32510. }
  32511. // Draw
  32512. this._draw(subMesh, fillMode);
  32513. }
  32514. }
  32515. }
  32516. return this;
  32517. };
  32518. /**
  32519. * Triggers the draw call for the mesh.
  32520. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32521. * Returns the Mesh.
  32522. */
  32523. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32524. this._checkOcclusionQuery();
  32525. if (this._isOccluded) {
  32526. return this;
  32527. }
  32528. var scene = this.getScene();
  32529. // Managing instances
  32530. var batch = this._getInstancesRenderList(subMesh._id);
  32531. if (batch.mustReturn) {
  32532. return this;
  32533. }
  32534. // Checking geometry state
  32535. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32536. return this;
  32537. }
  32538. this.onBeforeRenderObservable.notifyObservers(this);
  32539. var engine = scene.getEngine();
  32540. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32541. // Material
  32542. var material = subMesh.getMaterial();
  32543. if (!material) {
  32544. return this;
  32545. }
  32546. this._effectiveMaterial = material;
  32547. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32548. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32549. return this;
  32550. }
  32551. }
  32552. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32553. return this;
  32554. }
  32555. // Alpha mode
  32556. if (enableAlphaMode) {
  32557. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32558. }
  32559. // Outline - step 1
  32560. var savedDepthWrite = engine.getDepthWrite();
  32561. if (this.renderOutline) {
  32562. engine.setDepthWrite(false);
  32563. scene.getOutlineRenderer().render(subMesh, batch);
  32564. engine.setDepthWrite(savedDepthWrite);
  32565. }
  32566. var effect;
  32567. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32568. effect = subMesh.effect;
  32569. }
  32570. else {
  32571. effect = this._effectiveMaterial.getEffect();
  32572. }
  32573. if (!effect) {
  32574. return this;
  32575. }
  32576. var sideOrientation = this.overrideMaterialSideOrientation;
  32577. if (sideOrientation == null) {
  32578. sideOrientation = this._effectiveMaterial.sideOrientation;
  32579. if (this._getWorldMatrixDeterminant() < 0) {
  32580. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32581. }
  32582. }
  32583. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32584. if (this._effectiveMaterial.forceDepthWrite) {
  32585. engine.setDepthWrite(true);
  32586. }
  32587. // Bind
  32588. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32589. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32590. this._bind(subMesh, effect, fillMode);
  32591. }
  32592. var world = this.getWorldMatrix();
  32593. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32594. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32595. }
  32596. else {
  32597. this._effectiveMaterial.bind(world, this);
  32598. }
  32599. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32600. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32601. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32602. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32603. }
  32604. // Draw
  32605. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32606. // Unbind
  32607. this._effectiveMaterial.unbind();
  32608. // Outline - step 2
  32609. if (this.renderOutline && savedDepthWrite) {
  32610. engine.setDepthWrite(true);
  32611. engine.setColorWrite(false);
  32612. scene.getOutlineRenderer().render(subMesh, batch);
  32613. engine.setColorWrite(true);
  32614. }
  32615. // Overlay
  32616. if (this.renderOverlay) {
  32617. var currentMode = engine.getAlphaMode();
  32618. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32619. scene.getOutlineRenderer().render(subMesh, batch, true);
  32620. engine.setAlphaMode(currentMode);
  32621. }
  32622. this.onAfterRenderObservable.notifyObservers(this);
  32623. return this;
  32624. };
  32625. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32626. if (isInstance && effectiveMaterial) {
  32627. effectiveMaterial.bindOnlyWorldMatrix(world);
  32628. }
  32629. };
  32630. /**
  32631. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32632. */
  32633. Mesh.prototype.getEmittedParticleSystems = function () {
  32634. var results = new Array();
  32635. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32636. var particleSystem = this.getScene().particleSystems[index];
  32637. if (particleSystem.emitter === this) {
  32638. results.push(particleSystem);
  32639. }
  32640. }
  32641. return results;
  32642. };
  32643. /**
  32644. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32645. */
  32646. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32647. var results = new Array();
  32648. var descendants = this.getDescendants();
  32649. descendants.push(this);
  32650. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32651. var particleSystem = this.getScene().particleSystems[index];
  32652. var emitter = particleSystem.emitter;
  32653. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32654. results.push(particleSystem);
  32655. }
  32656. }
  32657. return results;
  32658. };
  32659. /**
  32660. * Normalize matrix weights so that all vertices have a total weight set to 1
  32661. */
  32662. Mesh.prototype.cleanMatrixWeights = function () {
  32663. var epsilon = 1e-3;
  32664. var noInfluenceBoneIndex = 0.0;
  32665. if (this.skeleton) {
  32666. noInfluenceBoneIndex = this.skeleton.bones.length;
  32667. }
  32668. else {
  32669. return;
  32670. }
  32671. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32672. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32673. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32674. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32675. var influencers = this.numBoneInfluencers;
  32676. var size = matricesWeights.length;
  32677. for (var i = 0; i < size; i += 4) {
  32678. var weight = 0.0;
  32679. var firstZeroWeight = -1;
  32680. for (var j = 0; j < 4; j++) {
  32681. var w = matricesWeights[i + j];
  32682. weight += w;
  32683. if (w < epsilon && firstZeroWeight < 0) {
  32684. firstZeroWeight = j;
  32685. }
  32686. }
  32687. if (matricesWeightsExtra) {
  32688. for (var j = 0; j < 4; j++) {
  32689. var w = matricesWeightsExtra[i + j];
  32690. weight += w;
  32691. if (w < epsilon && firstZeroWeight < 0) {
  32692. firstZeroWeight = j + 4;
  32693. }
  32694. }
  32695. }
  32696. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32697. firstZeroWeight = influencers - 1;
  32698. }
  32699. if (weight > epsilon) {
  32700. var mweight = 1.0 / weight;
  32701. for (var j = 0; j < 4; j++) {
  32702. matricesWeights[i + j] *= mweight;
  32703. }
  32704. if (matricesWeightsExtra) {
  32705. for (var j = 0; j < 4; j++) {
  32706. matricesWeightsExtra[i + j] *= mweight;
  32707. }
  32708. }
  32709. }
  32710. else {
  32711. if (firstZeroWeight >= 4) {
  32712. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32713. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32714. }
  32715. else {
  32716. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32717. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32718. }
  32719. }
  32720. }
  32721. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32722. if (matricesIndicesExtra) {
  32723. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32724. }
  32725. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32726. if (matricesWeightsExtra) {
  32727. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32728. }
  32729. };
  32730. Mesh.prototype._checkDelayState = function () {
  32731. var scene = this.getScene();
  32732. if (this._geometry) {
  32733. this._geometry.load(scene);
  32734. }
  32735. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32736. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32737. this._queueLoad(scene);
  32738. }
  32739. return this;
  32740. };
  32741. Mesh.prototype._queueLoad = function (scene) {
  32742. var _this = this;
  32743. scene._addPendingData(this);
  32744. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32745. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32746. if (data instanceof ArrayBuffer) {
  32747. _this._delayLoadingFunction(data, _this);
  32748. }
  32749. else {
  32750. _this._delayLoadingFunction(JSON.parse(data), _this);
  32751. }
  32752. _this.instances.forEach(function (instance) {
  32753. instance._syncSubMeshes();
  32754. });
  32755. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32756. scene._removePendingData(_this);
  32757. }, function () { }, scene.database, getBinaryData);
  32758. return this;
  32759. };
  32760. /**
  32761. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32762. */
  32763. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32764. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32765. return false;
  32766. }
  32767. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32768. return false;
  32769. }
  32770. this._checkDelayState();
  32771. return true;
  32772. };
  32773. /**
  32774. * Sets the mesh material by the material or multiMaterial `id` property.
  32775. * The material `id` is a string identifying the material or the multiMaterial.
  32776. * This method returns the Mesh.
  32777. */
  32778. Mesh.prototype.setMaterialByID = function (id) {
  32779. var materials = this.getScene().materials;
  32780. var index;
  32781. for (index = materials.length - 1; index > -1; index--) {
  32782. if (materials[index].id === id) {
  32783. this.material = materials[index];
  32784. return this;
  32785. }
  32786. }
  32787. // Multi
  32788. var multiMaterials = this.getScene().multiMaterials;
  32789. for (index = multiMaterials.length - 1; index > -1; index--) {
  32790. if (multiMaterials[index].id === id) {
  32791. this.material = multiMaterials[index];
  32792. return this;
  32793. }
  32794. }
  32795. return this;
  32796. };
  32797. /**
  32798. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32799. */
  32800. Mesh.prototype.getAnimatables = function () {
  32801. var results = new Array();
  32802. if (this.material) {
  32803. results.push(this.material);
  32804. }
  32805. if (this.skeleton) {
  32806. results.push(this.skeleton);
  32807. }
  32808. return results;
  32809. };
  32810. /**
  32811. * Modifies the mesh geometry according to the passed transformation matrix.
  32812. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32813. * The mesh normals are modified accordingly the same transformation.
  32814. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32815. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32816. * Returns the Mesh.
  32817. */
  32818. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32819. // Position
  32820. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32821. return this;
  32822. }
  32823. var submeshes = this.subMeshes.splice(0);
  32824. this._resetPointsArrayCache();
  32825. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32826. var temp = new Array();
  32827. var index;
  32828. for (index = 0; index < data.length; index += 3) {
  32829. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32830. }
  32831. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32832. // Normals
  32833. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32834. return this;
  32835. }
  32836. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32837. temp = [];
  32838. for (index = 0; index < data.length; index += 3) {
  32839. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32840. }
  32841. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32842. // flip faces?
  32843. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32844. this.flipFaces();
  32845. }
  32846. // Restore submeshes
  32847. this.releaseSubMeshes();
  32848. this.subMeshes = submeshes;
  32849. return this;
  32850. };
  32851. /**
  32852. * Modifies the mesh geometry according to its own current World Matrix.
  32853. * The mesh World Matrix is then reset.
  32854. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32855. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32856. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32857. * Returns the Mesh.
  32858. */
  32859. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32860. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32861. this.scaling.copyFromFloats(1, 1, 1);
  32862. this.position.copyFromFloats(0, 0, 0);
  32863. this.rotation.copyFromFloats(0, 0, 0);
  32864. //only if quaternion is already set
  32865. if (this.rotationQuaternion) {
  32866. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32867. }
  32868. this._worldMatrix = BABYLON.Matrix.Identity();
  32869. return this;
  32870. };
  32871. Object.defineProperty(Mesh.prototype, "_positions", {
  32872. // Cache
  32873. get: function () {
  32874. if (this._geometry) {
  32875. return this._geometry._positions;
  32876. }
  32877. return null;
  32878. },
  32879. enumerable: true,
  32880. configurable: true
  32881. });
  32882. Mesh.prototype._resetPointsArrayCache = function () {
  32883. if (this._geometry) {
  32884. this._geometry._resetPointsArrayCache();
  32885. }
  32886. return this;
  32887. };
  32888. Mesh.prototype._generatePointsArray = function () {
  32889. if (this._geometry) {
  32890. return this._geometry._generatePointsArray();
  32891. }
  32892. return false;
  32893. };
  32894. /**
  32895. * Returns a new Mesh object generated from the current mesh properties.
  32896. * This method must not get confused with createInstance().
  32897. * The parameter `name` is a string, the name given to the new mesh.
  32898. * The optional parameter `newParent` can be any Node object (default `null`).
  32899. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32900. * 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.
  32901. */
  32902. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32903. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32904. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32905. };
  32906. /**
  32907. * Releases resources associated with this mesh.
  32908. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32909. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32910. */
  32911. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32912. var _this = this;
  32913. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32914. this.morphTargetManager = null;
  32915. if (this._geometry) {
  32916. this._geometry.releaseForMesh(this, true);
  32917. }
  32918. // Sources
  32919. var meshes = this.getScene().meshes;
  32920. meshes.forEach(function (abstractMesh) {
  32921. var mesh = abstractMesh;
  32922. if (mesh._source && mesh._source === _this) {
  32923. mesh._source = null;
  32924. }
  32925. });
  32926. this._source = null;
  32927. // Instances
  32928. if (this._instancesBuffer) {
  32929. this._instancesBuffer.dispose();
  32930. this._instancesBuffer = null;
  32931. }
  32932. while (this.instances.length) {
  32933. this.instances[0].dispose();
  32934. }
  32935. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32936. };
  32937. /**
  32938. * Modifies the mesh geometry according to a displacement map.
  32939. * 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.
  32940. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32941. * This method returns nothing.
  32942. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32943. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32944. * 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.
  32945. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32946. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32947. *
  32948. * Returns the Mesh.
  32949. */
  32950. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32951. var _this = this;
  32952. var scene = this.getScene();
  32953. var onload = function (img) {
  32954. // Getting height map data
  32955. var canvas = document.createElement("canvas");
  32956. var context = canvas.getContext("2d");
  32957. var heightMapWidth = img.width;
  32958. var heightMapHeight = img.height;
  32959. canvas.width = heightMapWidth;
  32960. canvas.height = heightMapHeight;
  32961. context.drawImage(img, 0, 0);
  32962. // Create VertexData from map data
  32963. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32964. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32965. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32966. //execute success callback, if set
  32967. if (onSuccess) {
  32968. onSuccess(_this);
  32969. }
  32970. };
  32971. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32972. return this;
  32973. };
  32974. /**
  32975. * Modifies the mesh geometry according to a displacementMap buffer.
  32976. * 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.
  32977. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32978. * This method returns nothing.
  32979. * 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.
  32980. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32981. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32982. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32983. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32984. *
  32985. * Returns the Mesh.
  32986. */
  32987. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32988. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32989. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32990. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32991. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32992. return this;
  32993. }
  32994. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32995. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32996. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32997. var position = BABYLON.Vector3.Zero();
  32998. var normal = BABYLON.Vector3.Zero();
  32999. var uv = BABYLON.Vector2.Zero();
  33000. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33001. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33002. for (var index = 0; index < positions.length; index += 3) {
  33003. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33004. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33005. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33006. // Compute height
  33007. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33008. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33009. var pos = (u + v * heightMapWidth) * 4;
  33010. var r = buffer[pos] / 255.0;
  33011. var g = buffer[pos + 1] / 255.0;
  33012. var b = buffer[pos + 2] / 255.0;
  33013. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33014. normal.normalize();
  33015. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33016. position = position.add(normal);
  33017. position.toArray(positions, index);
  33018. }
  33019. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33020. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33021. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33022. return this;
  33023. };
  33024. /**
  33025. * Modify the mesh to get a flat shading rendering.
  33026. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33027. * This method returns the Mesh.
  33028. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33029. */
  33030. Mesh.prototype.convertToFlatShadedMesh = function () {
  33031. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33032. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33033. var kinds = this.getVerticesDataKinds();
  33034. var vbs = {};
  33035. var data = {};
  33036. var newdata = {};
  33037. var updatableNormals = false;
  33038. var kindIndex;
  33039. var kind;
  33040. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33041. kind = kinds[kindIndex];
  33042. var vertexBuffer = this.getVertexBuffer(kind);
  33043. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33044. updatableNormals = vertexBuffer.isUpdatable();
  33045. kinds.splice(kindIndex, 1);
  33046. kindIndex--;
  33047. continue;
  33048. }
  33049. vbs[kind] = vertexBuffer;
  33050. data[kind] = vbs[kind].getData();
  33051. newdata[kind] = [];
  33052. }
  33053. // Save previous submeshes
  33054. var previousSubmeshes = this.subMeshes.slice(0);
  33055. var indices = this.getIndices();
  33056. var totalIndices = this.getTotalIndices();
  33057. // Generating unique vertices per face
  33058. var index;
  33059. for (index = 0; index < totalIndices; index++) {
  33060. var vertexIndex = indices[index];
  33061. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33062. kind = kinds[kindIndex];
  33063. var stride = vbs[kind].getStrideSize();
  33064. for (var offset = 0; offset < stride; offset++) {
  33065. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33066. }
  33067. }
  33068. }
  33069. // Updating faces & normal
  33070. var normals = [];
  33071. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33072. for (index = 0; index < totalIndices; index += 3) {
  33073. indices[index] = index;
  33074. indices[index + 1] = index + 1;
  33075. indices[index + 2] = index + 2;
  33076. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33077. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33078. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33079. var p1p2 = p1.subtract(p2);
  33080. var p3p2 = p3.subtract(p2);
  33081. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33082. // Store same normals for every vertex
  33083. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33084. normals.push(normal.x);
  33085. normals.push(normal.y);
  33086. normals.push(normal.z);
  33087. }
  33088. }
  33089. this.setIndices(indices);
  33090. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33091. // Updating vertex buffers
  33092. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33093. kind = kinds[kindIndex];
  33094. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33095. }
  33096. // Updating submeshes
  33097. this.releaseSubMeshes();
  33098. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33099. var previousOne = previousSubmeshes[submeshIndex];
  33100. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33101. }
  33102. this.synchronizeInstances();
  33103. return this;
  33104. };
  33105. /**
  33106. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33107. * In other words, more vertices, no more indices and a single bigger VBO.
  33108. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33109. * Returns the Mesh.
  33110. */
  33111. Mesh.prototype.convertToUnIndexedMesh = function () {
  33112. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33113. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33114. var kinds = this.getVerticesDataKinds();
  33115. var vbs = {};
  33116. var data = {};
  33117. var newdata = {};
  33118. var kindIndex;
  33119. var kind;
  33120. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33121. kind = kinds[kindIndex];
  33122. var vertexBuffer = this.getVertexBuffer(kind);
  33123. vbs[kind] = vertexBuffer;
  33124. data[kind] = vbs[kind].getData();
  33125. newdata[kind] = [];
  33126. }
  33127. // Save previous submeshes
  33128. var previousSubmeshes = this.subMeshes.slice(0);
  33129. var indices = this.getIndices();
  33130. var totalIndices = this.getTotalIndices();
  33131. // Generating unique vertices per face
  33132. var index;
  33133. for (index = 0; index < totalIndices; index++) {
  33134. var vertexIndex = indices[index];
  33135. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33136. kind = kinds[kindIndex];
  33137. var stride = vbs[kind].getStrideSize();
  33138. for (var offset = 0; offset < stride; offset++) {
  33139. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33140. }
  33141. }
  33142. }
  33143. // Updating indices
  33144. for (index = 0; index < totalIndices; index += 3) {
  33145. indices[index] = index;
  33146. indices[index + 1] = index + 1;
  33147. indices[index + 2] = index + 2;
  33148. }
  33149. this.setIndices(indices);
  33150. // Updating vertex buffers
  33151. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33152. kind = kinds[kindIndex];
  33153. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33154. }
  33155. // Updating submeshes
  33156. this.releaseSubMeshes();
  33157. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33158. var previousOne = previousSubmeshes[submeshIndex];
  33159. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33160. }
  33161. this._unIndexed = true;
  33162. this.synchronizeInstances();
  33163. return this;
  33164. };
  33165. /**
  33166. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33167. * This method returns the Mesh.
  33168. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33169. */
  33170. Mesh.prototype.flipFaces = function (flipNormals) {
  33171. if (flipNormals === void 0) { flipNormals = false; }
  33172. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33173. var i;
  33174. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33175. for (i = 0; i < vertex_data.normals.length; i++) {
  33176. vertex_data.normals[i] *= -1;
  33177. }
  33178. }
  33179. if (vertex_data.indices) {
  33180. var temp;
  33181. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33182. // reassign indices
  33183. temp = vertex_data.indices[i + 1];
  33184. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33185. vertex_data.indices[i + 2] = temp;
  33186. }
  33187. }
  33188. vertex_data.applyToMesh(this);
  33189. return this;
  33190. };
  33191. // Instances
  33192. /**
  33193. * Creates a new InstancedMesh object from the mesh model.
  33194. * An instance shares the same properties and the same material than its model.
  33195. * Only these properties of each instance can then be set individually :
  33196. * - position
  33197. * - rotation
  33198. * - rotationQuaternion
  33199. * - setPivotMatrix
  33200. * - scaling
  33201. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33202. * Warning : this method is not supported for Line mesh and LineSystem
  33203. */
  33204. Mesh.prototype.createInstance = function (name) {
  33205. return new BABYLON.InstancedMesh(name, this);
  33206. };
  33207. /**
  33208. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33209. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33210. * This method returns the Mesh.
  33211. */
  33212. Mesh.prototype.synchronizeInstances = function () {
  33213. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33214. var instance = this.instances[instanceIndex];
  33215. instance._syncSubMeshes();
  33216. }
  33217. return this;
  33218. };
  33219. /**
  33220. * Simplify the mesh according to the given array of settings.
  33221. * Function will return immediately and will simplify async. It returns the Mesh.
  33222. * @param settings a collection of simplification settings.
  33223. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33224. * @param type the type of simplification to run.
  33225. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33226. */
  33227. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33228. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33229. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33230. this.getScene().simplificationQueue.addTask({
  33231. settings: settings,
  33232. parallelProcessing: parallelProcessing,
  33233. mesh: this,
  33234. simplificationType: simplificationType,
  33235. successCallback: successCallback
  33236. });
  33237. return this;
  33238. };
  33239. /**
  33240. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33241. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33242. * This should be used together with the simplification to avoid disappearing triangles.
  33243. * Returns the Mesh.
  33244. * @param successCallback an optional success callback to be called after the optimization finished.
  33245. */
  33246. Mesh.prototype.optimizeIndices = function (successCallback) {
  33247. var _this = this;
  33248. var indices = this.getIndices();
  33249. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33250. if (!positions || !indices) {
  33251. return this;
  33252. }
  33253. var vectorPositions = new Array();
  33254. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33255. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33256. }
  33257. var dupes = new Array();
  33258. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33259. var realPos = vectorPositions.length - 1 - iteration;
  33260. var testedPosition = vectorPositions[realPos];
  33261. for (var j = 0; j < realPos; ++j) {
  33262. var againstPosition = vectorPositions[j];
  33263. if (testedPosition.equals(againstPosition)) {
  33264. dupes[realPos] = j;
  33265. break;
  33266. }
  33267. }
  33268. }, function () {
  33269. for (var i = 0; i < indices.length; ++i) {
  33270. indices[i] = dupes[indices[i]] || indices[i];
  33271. }
  33272. //indices are now reordered
  33273. var originalSubMeshes = _this.subMeshes.slice(0);
  33274. _this.setIndices(indices);
  33275. _this.subMeshes = originalSubMeshes;
  33276. if (successCallback) {
  33277. successCallback(_this);
  33278. }
  33279. });
  33280. return this;
  33281. };
  33282. Mesh.prototype.serialize = function (serializationObject) {
  33283. serializationObject.name = this.name;
  33284. serializationObject.id = this.id;
  33285. serializationObject.type = this.getClassName();
  33286. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33287. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33288. }
  33289. serializationObject.position = this.position.asArray();
  33290. if (this.rotationQuaternion) {
  33291. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33292. }
  33293. else if (this.rotation) {
  33294. serializationObject.rotation = this.rotation.asArray();
  33295. }
  33296. serializationObject.scaling = this.scaling.asArray();
  33297. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33298. serializationObject.isEnabled = this.isEnabled(false);
  33299. serializationObject.isVisible = this.isVisible;
  33300. serializationObject.infiniteDistance = this.infiniteDistance;
  33301. serializationObject.pickable = this.isPickable;
  33302. serializationObject.receiveShadows = this.receiveShadows;
  33303. serializationObject.billboardMode = this.billboardMode;
  33304. serializationObject.visibility = this.visibility;
  33305. serializationObject.checkCollisions = this.checkCollisions;
  33306. serializationObject.isBlocker = this.isBlocker;
  33307. // Parent
  33308. if (this.parent) {
  33309. serializationObject.parentId = this.parent.id;
  33310. }
  33311. // Geometry
  33312. serializationObject.isUnIndexed = this.isUnIndexed;
  33313. var geometry = this._geometry;
  33314. if (geometry) {
  33315. var geometryId = geometry.id;
  33316. serializationObject.geometryId = geometryId;
  33317. // SubMeshes
  33318. serializationObject.subMeshes = [];
  33319. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33320. var subMesh = this.subMeshes[subIndex];
  33321. serializationObject.subMeshes.push({
  33322. materialIndex: subMesh.materialIndex,
  33323. verticesStart: subMesh.verticesStart,
  33324. verticesCount: subMesh.verticesCount,
  33325. indexStart: subMesh.indexStart,
  33326. indexCount: subMesh.indexCount
  33327. });
  33328. }
  33329. }
  33330. // Material
  33331. if (this.material) {
  33332. serializationObject.materialId = this.material.id;
  33333. }
  33334. else {
  33335. this.material = null;
  33336. }
  33337. // Morph targets
  33338. if (this.morphTargetManager) {
  33339. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33340. }
  33341. // Skeleton
  33342. if (this.skeleton) {
  33343. serializationObject.skeletonId = this.skeleton.id;
  33344. }
  33345. // Physics
  33346. //TODO implement correct serialization for physics impostors.
  33347. var impostor = this.getPhysicsImpostor();
  33348. if (impostor) {
  33349. serializationObject.physicsMass = impostor.getParam("mass");
  33350. serializationObject.physicsFriction = impostor.getParam("friction");
  33351. serializationObject.physicsRestitution = impostor.getParam("mass");
  33352. serializationObject.physicsImpostor = impostor.type;
  33353. }
  33354. // Metadata
  33355. if (this.metadata) {
  33356. serializationObject.metadata = this.metadata;
  33357. }
  33358. // Instances
  33359. serializationObject.instances = [];
  33360. for (var index = 0; index < this.instances.length; index++) {
  33361. var instance = this.instances[index];
  33362. var serializationInstance = {
  33363. name: instance.name,
  33364. id: instance.id,
  33365. position: instance.position.asArray(),
  33366. scaling: instance.scaling.asArray()
  33367. };
  33368. if (instance.rotationQuaternion) {
  33369. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33370. }
  33371. else if (instance.rotation) {
  33372. serializationInstance.rotation = instance.rotation.asArray();
  33373. }
  33374. serializationObject.instances.push(serializationInstance);
  33375. // Animations
  33376. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33377. serializationInstance.ranges = instance.serializeAnimationRanges();
  33378. }
  33379. //
  33380. // Animations
  33381. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33382. serializationObject.ranges = this.serializeAnimationRanges();
  33383. // Layer mask
  33384. serializationObject.layerMask = this.layerMask;
  33385. // Alpha
  33386. serializationObject.alphaIndex = this.alphaIndex;
  33387. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33388. // Overlay
  33389. serializationObject.overlayAlpha = this.overlayAlpha;
  33390. serializationObject.overlayColor = this.overlayColor.asArray();
  33391. serializationObject.renderOverlay = this.renderOverlay;
  33392. // Fog
  33393. serializationObject.applyFog = this.applyFog;
  33394. // Action Manager
  33395. if (this.actionManager) {
  33396. serializationObject.actions = this.actionManager.serialize(this.name);
  33397. }
  33398. };
  33399. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33400. if (!this.geometry) {
  33401. return;
  33402. }
  33403. this._markSubMeshesAsAttributesDirty();
  33404. var morphTargetManager = this._morphTargetManager;
  33405. if (morphTargetManager && morphTargetManager.vertexCount) {
  33406. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33407. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33408. this.morphTargetManager = null;
  33409. return;
  33410. }
  33411. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33412. var morphTarget = morphTargetManager.getActiveTarget(index);
  33413. var positions = morphTarget.getPositions();
  33414. if (!positions) {
  33415. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33416. return;
  33417. }
  33418. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33419. var normals = morphTarget.getNormals();
  33420. if (normals) {
  33421. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33422. }
  33423. var tangents = morphTarget.getTangents();
  33424. if (tangents) {
  33425. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33426. }
  33427. }
  33428. }
  33429. else {
  33430. var index = 0;
  33431. // Positions
  33432. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33433. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33434. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33435. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33436. }
  33437. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33438. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33439. }
  33440. index++;
  33441. }
  33442. }
  33443. };
  33444. // Statics
  33445. /**
  33446. * Returns a new Mesh object parsed from the source provided.
  33447. * The parameter `parsedMesh` is the source.
  33448. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33449. */
  33450. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33451. var mesh;
  33452. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33453. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33454. }
  33455. else {
  33456. mesh = new Mesh(parsedMesh.name, scene);
  33457. }
  33458. mesh.id = parsedMesh.id;
  33459. if (BABYLON.Tags) {
  33460. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33461. }
  33462. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33463. if (parsedMesh.metadata !== undefined) {
  33464. mesh.metadata = parsedMesh.metadata;
  33465. }
  33466. if (parsedMesh.rotationQuaternion) {
  33467. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33468. }
  33469. else if (parsedMesh.rotation) {
  33470. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33471. }
  33472. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33473. if (parsedMesh.localMatrix) {
  33474. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33475. }
  33476. else if (parsedMesh.pivotMatrix) {
  33477. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33478. }
  33479. mesh.setEnabled(parsedMesh.isEnabled);
  33480. mesh.isVisible = parsedMesh.isVisible;
  33481. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33482. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33483. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33484. if (parsedMesh.applyFog !== undefined) {
  33485. mesh.applyFog = parsedMesh.applyFog;
  33486. }
  33487. if (parsedMesh.pickable !== undefined) {
  33488. mesh.isPickable = parsedMesh.pickable;
  33489. }
  33490. if (parsedMesh.alphaIndex !== undefined) {
  33491. mesh.alphaIndex = parsedMesh.alphaIndex;
  33492. }
  33493. mesh.receiveShadows = parsedMesh.receiveShadows;
  33494. mesh.billboardMode = parsedMesh.billboardMode;
  33495. if (parsedMesh.visibility !== undefined) {
  33496. mesh.visibility = parsedMesh.visibility;
  33497. }
  33498. mesh.checkCollisions = parsedMesh.checkCollisions;
  33499. if (parsedMesh.isBlocker !== undefined) {
  33500. mesh.isBlocker = parsedMesh.isBlocker;
  33501. }
  33502. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33503. // freezeWorldMatrix
  33504. if (parsedMesh.freezeWorldMatrix) {
  33505. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33506. }
  33507. // Parent
  33508. if (parsedMesh.parentId) {
  33509. mesh._waitingParentId = parsedMesh.parentId;
  33510. }
  33511. // Actions
  33512. if (parsedMesh.actions !== undefined) {
  33513. mesh._waitingActions = parsedMesh.actions;
  33514. }
  33515. // Overlay
  33516. if (parsedMesh.overlayAlpha !== undefined) {
  33517. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33518. }
  33519. if (parsedMesh.overlayColor !== undefined) {
  33520. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33521. }
  33522. if (parsedMesh.renderOverlay !== undefined) {
  33523. mesh.renderOverlay = parsedMesh.renderOverlay;
  33524. }
  33525. // Geometry
  33526. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33527. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33528. if (parsedMesh.delayLoadingFile) {
  33529. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33530. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33531. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33532. if (parsedMesh._binaryInfo) {
  33533. mesh._binaryInfo = parsedMesh._binaryInfo;
  33534. }
  33535. mesh._delayInfo = [];
  33536. if (parsedMesh.hasUVs) {
  33537. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33538. }
  33539. if (parsedMesh.hasUVs2) {
  33540. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33541. }
  33542. if (parsedMesh.hasUVs3) {
  33543. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33544. }
  33545. if (parsedMesh.hasUVs4) {
  33546. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33547. }
  33548. if (parsedMesh.hasUVs5) {
  33549. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33550. }
  33551. if (parsedMesh.hasUVs6) {
  33552. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33553. }
  33554. if (parsedMesh.hasColors) {
  33555. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33556. }
  33557. if (parsedMesh.hasMatricesIndices) {
  33558. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33559. }
  33560. if (parsedMesh.hasMatricesWeights) {
  33561. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33562. }
  33563. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33564. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33565. mesh._checkDelayState();
  33566. }
  33567. }
  33568. else {
  33569. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33570. }
  33571. // Material
  33572. if (parsedMesh.materialId) {
  33573. mesh.setMaterialByID(parsedMesh.materialId);
  33574. }
  33575. else {
  33576. mesh.material = null;
  33577. }
  33578. // Morph targets
  33579. if (parsedMesh.morphTargetManagerId > -1) {
  33580. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33581. }
  33582. // Skeleton
  33583. if (parsedMesh.skeletonId > -1) {
  33584. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33585. if (parsedMesh.numBoneInfluencers) {
  33586. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33587. }
  33588. }
  33589. // Animations
  33590. if (parsedMesh.animations) {
  33591. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33592. var parsedAnimation = parsedMesh.animations[animationIndex];
  33593. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33594. }
  33595. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33596. }
  33597. if (parsedMesh.autoAnimate) {
  33598. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33599. }
  33600. // Layer Mask
  33601. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33602. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33603. }
  33604. else {
  33605. mesh.layerMask = 0x0FFFFFFF;
  33606. }
  33607. // Physics
  33608. if (parsedMesh.physicsImpostor) {
  33609. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33610. mass: parsedMesh.physicsMass,
  33611. friction: parsedMesh.physicsFriction,
  33612. restitution: parsedMesh.physicsRestitution
  33613. }, scene);
  33614. }
  33615. // Instances
  33616. if (parsedMesh.instances) {
  33617. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33618. var parsedInstance = parsedMesh.instances[index];
  33619. var instance = mesh.createInstance(parsedInstance.name);
  33620. if (parsedInstance.id) {
  33621. instance.id = parsedInstance.id;
  33622. }
  33623. if (BABYLON.Tags) {
  33624. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33625. }
  33626. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33627. if (parsedInstance.parentId) {
  33628. instance._waitingParentId = parsedInstance.parentId;
  33629. }
  33630. if (parsedInstance.rotationQuaternion) {
  33631. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33632. }
  33633. else if (parsedInstance.rotation) {
  33634. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33635. }
  33636. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33637. instance.checkCollisions = mesh.checkCollisions;
  33638. if (parsedMesh.animations) {
  33639. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33640. parsedAnimation = parsedMesh.animations[animationIndex];
  33641. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33642. }
  33643. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33644. if (parsedMesh.autoAnimate) {
  33645. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33646. }
  33647. }
  33648. }
  33649. }
  33650. return mesh;
  33651. };
  33652. /**
  33653. * Creates a ribbon mesh.
  33654. * Please consider using the same method from the MeshBuilder class instead.
  33655. * 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.
  33656. *
  33657. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33658. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33659. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33660. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33661. * 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.
  33662. * 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.
  33663. * 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
  33664. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33665. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33667. */
  33668. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33669. if (closeArray === void 0) { closeArray = false; }
  33670. if (updatable === void 0) { updatable = false; }
  33671. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33672. pathArray: pathArray,
  33673. closeArray: closeArray,
  33674. closePath: closePath,
  33675. offset: offset,
  33676. updatable: updatable,
  33677. sideOrientation: sideOrientation,
  33678. instance: instance
  33679. }, scene);
  33680. };
  33681. /**
  33682. * Creates a plane polygonal mesh. By default, this is a disc.
  33683. * Please consider using the same method from the MeshBuilder class instead.
  33684. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33685. * 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.
  33686. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33687. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33689. */
  33690. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33691. if (scene === void 0) { scene = null; }
  33692. var options = {
  33693. radius: radius,
  33694. tessellation: tessellation,
  33695. sideOrientation: sideOrientation,
  33696. updatable: updatable
  33697. };
  33698. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33699. };
  33700. /**
  33701. * Creates a box mesh.
  33702. * Please consider using the same method from the MeshBuilder class instead.
  33703. * The parameter `size` sets the size (float) of each box side (default 1).
  33704. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33705. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33706. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33707. */
  33708. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33709. if (scene === void 0) { scene = null; }
  33710. var options = {
  33711. size: size,
  33712. sideOrientation: sideOrientation,
  33713. updatable: updatable
  33714. };
  33715. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33716. };
  33717. /**
  33718. * Creates a sphere mesh.
  33719. * Please consider using the same method from the MeshBuilder class instead.
  33720. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33721. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33722. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33723. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33724. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33725. */
  33726. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33727. var options = {
  33728. segments: segments,
  33729. diameterX: diameter,
  33730. diameterY: diameter,
  33731. diameterZ: diameter,
  33732. sideOrientation: sideOrientation,
  33733. updatable: updatable
  33734. };
  33735. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33736. };
  33737. /**
  33738. * Creates a cylinder or a cone mesh.
  33739. * Please consider using the same method from the MeshBuilder class instead.
  33740. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33741. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33742. * 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.
  33743. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33744. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33745. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33746. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33748. */
  33749. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33750. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33751. if (scene !== undefined) {
  33752. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33753. updatable = scene;
  33754. }
  33755. scene = subdivisions;
  33756. subdivisions = 1;
  33757. }
  33758. var options = {
  33759. height: height,
  33760. diameterTop: diameterTop,
  33761. diameterBottom: diameterBottom,
  33762. tessellation: tessellation,
  33763. subdivisions: subdivisions,
  33764. sideOrientation: sideOrientation,
  33765. updatable: updatable
  33766. };
  33767. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33768. };
  33769. // Torus (Code from SharpDX.org)
  33770. /**
  33771. * Creates a torus mesh.
  33772. * Please consider using the same method from the MeshBuilder class instead.
  33773. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33774. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33775. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33777. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33778. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33779. */
  33780. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33781. var options = {
  33782. diameter: diameter,
  33783. thickness: thickness,
  33784. tessellation: tessellation,
  33785. sideOrientation: sideOrientation,
  33786. updatable: updatable
  33787. };
  33788. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33789. };
  33790. /**
  33791. * Creates a torus knot mesh.
  33792. * Please consider using the same method from the MeshBuilder class instead.
  33793. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33794. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33795. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33796. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33797. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33798. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33799. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33800. */
  33801. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33802. var options = {
  33803. radius: radius,
  33804. tube: tube,
  33805. radialSegments: radialSegments,
  33806. tubularSegments: tubularSegments,
  33807. p: p,
  33808. q: q,
  33809. sideOrientation: sideOrientation,
  33810. updatable: updatable
  33811. };
  33812. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33813. };
  33814. /**
  33815. * Creates a line mesh.
  33816. * Please consider using the same method from the MeshBuilder class instead.
  33817. * 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.
  33818. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33819. * The parameter `points` is an array successive Vector3.
  33820. * 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
  33821. * When updating an instance, remember that only point positions can change, not the number of points.
  33822. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33823. */
  33824. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33825. if (scene === void 0) { scene = null; }
  33826. if (updatable === void 0) { updatable = false; }
  33827. if (instance === void 0) { instance = null; }
  33828. var options = {
  33829. points: points,
  33830. updatable: updatable,
  33831. instance: instance
  33832. };
  33833. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33834. };
  33835. /**
  33836. * Creates a dashed line mesh.
  33837. * Please consider using the same method from the MeshBuilder class instead.
  33838. * 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.
  33839. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33840. * The parameter `points` is an array successive Vector3.
  33841. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33842. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33843. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33844. * 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
  33845. * When updating an instance, remember that only point positions can change, not the number of points.
  33846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33847. */
  33848. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33849. if (scene === void 0) { scene = null; }
  33850. var options = {
  33851. points: points,
  33852. dashSize: dashSize,
  33853. gapSize: gapSize,
  33854. dashNb: dashNb,
  33855. updatable: updatable,
  33856. instance: instance
  33857. };
  33858. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33859. };
  33860. /**
  33861. * Creates a polygon mesh.
  33862. * Please consider using the same method from the MeshBuilder class instead.
  33863. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33864. * 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.
  33865. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33867. * Remember you can only change the shape positions, not their number when updating a polygon.
  33868. */
  33869. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33870. var options = {
  33871. shape: shape,
  33872. holes: holes,
  33873. updatable: updatable,
  33874. sideOrientation: sideOrientation
  33875. };
  33876. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33877. };
  33878. /**
  33879. * Creates an extruded polygon mesh, with depth in the Y direction.
  33880. * Please consider using the same method from the MeshBuilder class instead.
  33881. */
  33882. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33883. var options = {
  33884. shape: shape,
  33885. holes: holes,
  33886. depth: depth,
  33887. updatable: updatable,
  33888. sideOrientation: sideOrientation
  33889. };
  33890. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33891. };
  33892. /**
  33893. * Creates an extruded shape mesh.
  33894. * 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.
  33895. * Please consider using the same method from the MeshBuilder class instead.
  33896. *
  33897. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33898. * 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
  33899. * extruded along the Z axis.
  33900. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33901. * 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.
  33902. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33903. * 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
  33904. * 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
  33905. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33907. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33908. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33909. */
  33910. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33911. if (scene === void 0) { scene = null; }
  33912. var options = {
  33913. shape: shape,
  33914. path: path,
  33915. scale: scale,
  33916. rotation: rotation,
  33917. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33918. sideOrientation: sideOrientation,
  33919. instance: instance,
  33920. updatable: updatable
  33921. };
  33922. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33923. };
  33924. /**
  33925. * Creates an custom extruded shape mesh.
  33926. * 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.
  33927. * Please consider using the same method from the MeshBuilder class instead.
  33928. *
  33929. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33930. * 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
  33931. * extruded along the Z axis.
  33932. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33933. * 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
  33934. * and the distance of this point from the begining of the path :
  33935. * ```javascript
  33936. * var rotationFunction = function(i, distance) {
  33937. * // do things
  33938. * return rotationValue; }
  33939. * ```
  33940. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33941. * 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
  33942. * and the distance of this point from the begining of the path :
  33943. * ```javascript
  33944. * var scaleFunction = function(i, distance) {
  33945. * // do things
  33946. * return scaleValue;}
  33947. * ```
  33948. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33949. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33950. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33951. * 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
  33952. * 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
  33953. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33954. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33955. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33956. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33957. */
  33958. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33959. var options = {
  33960. shape: shape,
  33961. path: path,
  33962. scaleFunction: scaleFunction,
  33963. rotationFunction: rotationFunction,
  33964. ribbonCloseArray: ribbonCloseArray,
  33965. ribbonClosePath: ribbonClosePath,
  33966. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33967. sideOrientation: sideOrientation,
  33968. instance: instance,
  33969. updatable: updatable
  33970. };
  33971. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33972. };
  33973. /**
  33974. * Creates lathe mesh.
  33975. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33976. * Please consider using the same method from the MeshBuilder class instead.
  33977. * 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
  33978. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33979. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33980. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33981. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33982. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33984. */
  33985. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33986. var options = {
  33987. shape: shape,
  33988. radius: radius,
  33989. tessellation: tessellation,
  33990. sideOrientation: sideOrientation,
  33991. updatable: updatable
  33992. };
  33993. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33994. };
  33995. /**
  33996. * Creates a plane mesh.
  33997. * Please consider using the same method from the MeshBuilder class instead.
  33998. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33999. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34000. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34002. */
  34003. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34004. var options = {
  34005. size: size,
  34006. width: size,
  34007. height: size,
  34008. sideOrientation: sideOrientation,
  34009. updatable: updatable
  34010. };
  34011. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34012. };
  34013. /**
  34014. * Creates a ground mesh.
  34015. * Please consider using the same method from the MeshBuilder class instead.
  34016. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34017. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34019. */
  34020. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34021. var options = {
  34022. width: width,
  34023. height: height,
  34024. subdivisions: subdivisions,
  34025. updatable: updatable
  34026. };
  34027. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34028. };
  34029. /**
  34030. * Creates a tiled ground mesh.
  34031. * Please consider using the same method from the MeshBuilder class instead.
  34032. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34033. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34034. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34035. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34036. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34037. * numbers of subdivisions on the ground width and height of each tile.
  34038. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34039. */
  34040. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34041. var options = {
  34042. xmin: xmin,
  34043. zmin: zmin,
  34044. xmax: xmax,
  34045. zmax: zmax,
  34046. subdivisions: subdivisions,
  34047. precision: precision,
  34048. updatable: updatable
  34049. };
  34050. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34051. };
  34052. /**
  34053. * Creates a ground mesh from a height map.
  34054. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34055. * Please consider using the same method from the MeshBuilder class instead.
  34056. * The parameter `url` sets the URL of the height map image resource.
  34057. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34058. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34059. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34060. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34061. * 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).
  34062. * This function is passed the newly built mesh :
  34063. * ```javascript
  34064. * function(mesh) { // do things
  34065. * return; }
  34066. * ```
  34067. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34068. */
  34069. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34070. var options = {
  34071. width: width,
  34072. height: height,
  34073. subdivisions: subdivisions,
  34074. minHeight: minHeight,
  34075. maxHeight: maxHeight,
  34076. updatable: updatable,
  34077. onReady: onReady
  34078. };
  34079. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34080. };
  34081. /**
  34082. * Creates a tube mesh.
  34083. * 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.
  34084. * Please consider using the same method from the MeshBuilder class instead.
  34085. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34086. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34087. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34088. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34089. * 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.
  34090. * It must return a radius value (positive float) :
  34091. * ```javascript
  34092. * var radiusFunction = function(i, distance) {
  34093. * // do things
  34094. * return radius; }
  34095. * ```
  34096. * 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
  34097. * 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
  34098. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34099. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34100. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34101. */
  34102. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34103. var options = {
  34104. path: path,
  34105. radius: radius,
  34106. tessellation: tessellation,
  34107. radiusFunction: radiusFunction,
  34108. arc: 1,
  34109. cap: cap,
  34110. updatable: updatable,
  34111. sideOrientation: sideOrientation,
  34112. instance: instance
  34113. };
  34114. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34115. };
  34116. /**
  34117. * Creates a polyhedron mesh.
  34118. * Please consider using the same method from the MeshBuilder class instead.
  34119. * 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
  34120. * to choose the wanted type.
  34121. * The parameter `size` (positive float, default 1) sets the polygon size.
  34122. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34123. * 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`.
  34124. * 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
  34125. * 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)`).
  34126. * 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
  34127. * 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.
  34128. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34129. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34130. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34131. */
  34132. Mesh.CreatePolyhedron = function (name, options, scene) {
  34133. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34134. };
  34135. /**
  34136. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34137. * Please consider using the same method from the MeshBuilder class instead.
  34138. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34139. * 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`).
  34140. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34141. * 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.
  34142. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34143. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34144. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34145. */
  34146. Mesh.CreateIcoSphere = function (name, options, scene) {
  34147. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34148. };
  34149. /**
  34150. * Creates a decal mesh.
  34151. * Please consider using the same method from the MeshBuilder class instead.
  34152. * 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.
  34153. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34154. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34155. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34156. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34157. */
  34158. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34159. var options = {
  34160. position: position,
  34161. normal: normal,
  34162. size: size,
  34163. angle: angle
  34164. };
  34165. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34166. };
  34167. // Skeletons
  34168. /**
  34169. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34170. */
  34171. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34172. if (!this._sourcePositions) {
  34173. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34174. if (!source) {
  34175. return this._sourcePositions;
  34176. }
  34177. this._sourcePositions = new Float32Array(source);
  34178. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34179. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34180. }
  34181. }
  34182. return this._sourcePositions;
  34183. };
  34184. /**
  34185. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34186. */
  34187. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34188. if (!this._sourceNormals) {
  34189. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34190. if (!source) {
  34191. return this._sourceNormals;
  34192. }
  34193. this._sourceNormals = new Float32Array(source);
  34194. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34195. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34196. }
  34197. }
  34198. return this._sourceNormals;
  34199. };
  34200. /**
  34201. * Updates the vertex buffer by applying transformation from the bones.
  34202. * Returns the Mesh.
  34203. *
  34204. * @param {skeleton} skeleton to apply
  34205. */
  34206. Mesh.prototype.applySkeleton = function (skeleton) {
  34207. if (!this.geometry) {
  34208. return this;
  34209. }
  34210. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34211. return this;
  34212. }
  34213. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34214. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34215. return this;
  34216. }
  34217. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34218. return this;
  34219. }
  34220. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34221. return this;
  34222. }
  34223. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34224. return this;
  34225. }
  34226. if (!this._sourcePositions) {
  34227. var submeshes = this.subMeshes.slice();
  34228. this.setPositionsForCPUSkinning();
  34229. this.subMeshes = submeshes;
  34230. }
  34231. if (!this._sourceNormals) {
  34232. this.setNormalsForCPUSkinning();
  34233. }
  34234. // positionsData checks for not being Float32Array will only pass at most once
  34235. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34236. if (!positionsData) {
  34237. return this;
  34238. }
  34239. if (!(positionsData instanceof Float32Array)) {
  34240. positionsData = new Float32Array(positionsData);
  34241. }
  34242. // normalsData checks for not being Float32Array will only pass at most once
  34243. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34244. if (!normalsData) {
  34245. return this;
  34246. }
  34247. if (!(normalsData instanceof Float32Array)) {
  34248. normalsData = new Float32Array(normalsData);
  34249. }
  34250. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34251. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34252. if (!matricesWeightsData || !matricesIndicesData) {
  34253. return this;
  34254. }
  34255. var needExtras = this.numBoneInfluencers > 4;
  34256. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34257. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34258. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34259. var tempVector3 = BABYLON.Vector3.Zero();
  34260. var finalMatrix = new BABYLON.Matrix();
  34261. var tempMatrix = new BABYLON.Matrix();
  34262. var matWeightIdx = 0;
  34263. var inf;
  34264. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34265. var weight;
  34266. for (inf = 0; inf < 4; inf++) {
  34267. weight = matricesWeightsData[matWeightIdx + inf];
  34268. if (weight > 0) {
  34269. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34270. finalMatrix.addToSelf(tempMatrix);
  34271. }
  34272. else
  34273. break;
  34274. }
  34275. if (needExtras) {
  34276. for (inf = 0; inf < 4; inf++) {
  34277. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34278. if (weight > 0) {
  34279. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34280. finalMatrix.addToSelf(tempMatrix);
  34281. }
  34282. else
  34283. break;
  34284. }
  34285. }
  34286. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34287. tempVector3.toArray(positionsData, index);
  34288. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34289. tempVector3.toArray(normalsData, index);
  34290. finalMatrix.reset();
  34291. }
  34292. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34293. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34294. return this;
  34295. };
  34296. // Tools
  34297. /**
  34298. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34299. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34300. */
  34301. Mesh.MinMax = function (meshes) {
  34302. var minVector = null;
  34303. var maxVector = null;
  34304. meshes.forEach(function (mesh, index, array) {
  34305. var boundingInfo = mesh.getBoundingInfo();
  34306. var boundingBox = boundingInfo.boundingBox;
  34307. if (!minVector || !maxVector) {
  34308. minVector = boundingBox.minimumWorld;
  34309. maxVector = boundingBox.maximumWorld;
  34310. }
  34311. else {
  34312. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34313. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34314. }
  34315. });
  34316. if (!minVector || !maxVector) {
  34317. return {
  34318. min: BABYLON.Vector3.Zero(),
  34319. max: BABYLON.Vector3.Zero()
  34320. };
  34321. }
  34322. return {
  34323. min: minVector,
  34324. max: maxVector
  34325. };
  34326. };
  34327. /**
  34328. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34329. */
  34330. Mesh.Center = function (meshesOrMinMaxVector) {
  34331. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34332. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34333. };
  34334. /**
  34335. * Merge the array of meshes into a single mesh for performance reasons.
  34336. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34337. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34338. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34339. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34340. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34341. */
  34342. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34343. if (disposeSource === void 0) { disposeSource = true; }
  34344. var index;
  34345. if (!allow32BitsIndices) {
  34346. var totalVertices = 0;
  34347. // Counting vertices
  34348. for (index = 0; index < meshes.length; index++) {
  34349. if (meshes[index]) {
  34350. totalVertices += meshes[index].getTotalVertices();
  34351. if (totalVertices > 65536) {
  34352. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34353. return null;
  34354. }
  34355. }
  34356. }
  34357. }
  34358. // Merge
  34359. var vertexData = null;
  34360. var otherVertexData;
  34361. var indiceArray = new Array();
  34362. var source = null;
  34363. for (index = 0; index < meshes.length; index++) {
  34364. if (meshes[index]) {
  34365. meshes[index].computeWorldMatrix(true);
  34366. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34367. otherVertexData.transform(meshes[index].getWorldMatrix());
  34368. if (vertexData) {
  34369. vertexData.merge(otherVertexData);
  34370. }
  34371. else {
  34372. vertexData = otherVertexData;
  34373. source = meshes[index];
  34374. }
  34375. if (subdivideWithSubMeshes) {
  34376. indiceArray.push(meshes[index].getTotalIndices());
  34377. }
  34378. }
  34379. }
  34380. source = source;
  34381. if (!meshSubclass) {
  34382. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34383. }
  34384. vertexData.applyToMesh(meshSubclass);
  34385. // Setting properties
  34386. meshSubclass.material = source.material;
  34387. meshSubclass.checkCollisions = source.checkCollisions;
  34388. // Cleaning
  34389. if (disposeSource) {
  34390. for (index = 0; index < meshes.length; index++) {
  34391. if (meshes[index]) {
  34392. meshes[index].dispose();
  34393. }
  34394. }
  34395. }
  34396. // Subdivide
  34397. if (subdivideWithSubMeshes) {
  34398. //-- removal of global submesh
  34399. meshSubclass.releaseSubMeshes();
  34400. index = 0;
  34401. var offset = 0;
  34402. //-- apply subdivision according to index table
  34403. while (index < indiceArray.length) {
  34404. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34405. offset += indiceArray[index];
  34406. index++;
  34407. }
  34408. }
  34409. return meshSubclass;
  34410. };
  34411. // Consts
  34412. Mesh._FRONTSIDE = 0;
  34413. Mesh._BACKSIDE = 1;
  34414. Mesh._DOUBLESIDE = 2;
  34415. Mesh._DEFAULTSIDE = 0;
  34416. Mesh._NO_CAP = 0;
  34417. Mesh._CAP_START = 1;
  34418. Mesh._CAP_END = 2;
  34419. Mesh._CAP_ALL = 3;
  34420. return Mesh;
  34421. }(BABYLON.AbstractMesh));
  34422. BABYLON.Mesh = Mesh;
  34423. })(BABYLON || (BABYLON = {}));
  34424. //# sourceMappingURL=babylon.mesh.js.map
  34425. var BABYLON;
  34426. (function (BABYLON) {
  34427. var BaseSubMesh = /** @class */ (function () {
  34428. function BaseSubMesh() {
  34429. }
  34430. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34431. get: function () {
  34432. return this._materialEffect;
  34433. },
  34434. enumerable: true,
  34435. configurable: true
  34436. });
  34437. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34438. if (defines === void 0) { defines = null; }
  34439. if (this._materialEffect === effect) {
  34440. if (!effect) {
  34441. this._materialDefines = null;
  34442. }
  34443. return;
  34444. }
  34445. this._materialDefines = defines;
  34446. this._materialEffect = effect;
  34447. };
  34448. return BaseSubMesh;
  34449. }());
  34450. BABYLON.BaseSubMesh = BaseSubMesh;
  34451. var SubMesh = /** @class */ (function (_super) {
  34452. __extends(SubMesh, _super);
  34453. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34454. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34455. var _this = _super.call(this) || this;
  34456. _this.materialIndex = materialIndex;
  34457. _this.verticesStart = verticesStart;
  34458. _this.verticesCount = verticesCount;
  34459. _this.indexStart = indexStart;
  34460. _this.indexCount = indexCount;
  34461. _this._renderId = 0;
  34462. _this._mesh = mesh;
  34463. _this._renderingMesh = renderingMesh || mesh;
  34464. mesh.subMeshes.push(_this);
  34465. _this._trianglePlanes = [];
  34466. _this._id = mesh.subMeshes.length - 1;
  34467. if (createBoundingBox) {
  34468. _this.refreshBoundingInfo();
  34469. mesh.computeWorldMatrix(true);
  34470. }
  34471. return _this;
  34472. }
  34473. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34474. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34475. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34476. };
  34477. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34478. get: function () {
  34479. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34480. },
  34481. enumerable: true,
  34482. configurable: true
  34483. });
  34484. /**
  34485. * Returns the submesh BoudingInfo object.
  34486. */
  34487. SubMesh.prototype.getBoundingInfo = function () {
  34488. if (this.IsGlobal) {
  34489. return this._mesh.getBoundingInfo();
  34490. }
  34491. return this._boundingInfo;
  34492. };
  34493. /**
  34494. * Sets the submesh BoundingInfo.
  34495. * Return the SubMesh.
  34496. */
  34497. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34498. this._boundingInfo = boundingInfo;
  34499. return this;
  34500. };
  34501. /**
  34502. * Returns the mesh of the current submesh.
  34503. */
  34504. SubMesh.prototype.getMesh = function () {
  34505. return this._mesh;
  34506. };
  34507. /**
  34508. * Returns the rendering mesh of the submesh.
  34509. */
  34510. SubMesh.prototype.getRenderingMesh = function () {
  34511. return this._renderingMesh;
  34512. };
  34513. /**
  34514. * Returns the submesh material.
  34515. */
  34516. SubMesh.prototype.getMaterial = function () {
  34517. var rootMaterial = this._renderingMesh.material;
  34518. if (rootMaterial === null || rootMaterial === undefined) {
  34519. return this._mesh.getScene().defaultMaterial;
  34520. }
  34521. else if (rootMaterial.getSubMaterial) {
  34522. var multiMaterial = rootMaterial;
  34523. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34524. if (this._currentMaterial !== effectiveMaterial) {
  34525. this._currentMaterial = effectiveMaterial;
  34526. this._materialDefines = null;
  34527. }
  34528. return effectiveMaterial;
  34529. }
  34530. return rootMaterial;
  34531. };
  34532. // Methods
  34533. /**
  34534. * Sets a new updated BoundingInfo object to the submesh.
  34535. * Returns the SubMesh.
  34536. */
  34537. SubMesh.prototype.refreshBoundingInfo = function () {
  34538. this._lastColliderWorldVertices = null;
  34539. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34540. return this;
  34541. }
  34542. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34543. if (!data) {
  34544. this._boundingInfo = this._mesh.getBoundingInfo();
  34545. return this;
  34546. }
  34547. var indices = this._renderingMesh.getIndices();
  34548. var extend;
  34549. //is this the only submesh?
  34550. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34551. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34552. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34553. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34554. }
  34555. else {
  34556. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34557. }
  34558. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34559. return this;
  34560. };
  34561. SubMesh.prototype._checkCollision = function (collider) {
  34562. var boundingInfo = this.getBoundingInfo();
  34563. return boundingInfo._checkCollision(collider);
  34564. };
  34565. /**
  34566. * Updates the submesh BoundingInfo.
  34567. * Returns the Submesh.
  34568. */
  34569. SubMesh.prototype.updateBoundingInfo = function (world) {
  34570. var boundingInfo = this.getBoundingInfo();
  34571. if (!boundingInfo) {
  34572. this.refreshBoundingInfo();
  34573. boundingInfo = this.getBoundingInfo();
  34574. }
  34575. boundingInfo.update(world);
  34576. return this;
  34577. };
  34578. /**
  34579. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34580. * Boolean returned.
  34581. */
  34582. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34583. var boundingInfo = this.getBoundingInfo();
  34584. if (!boundingInfo) {
  34585. return false;
  34586. }
  34587. return boundingInfo.isInFrustum(frustumPlanes);
  34588. };
  34589. /**
  34590. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34591. * Boolean returned.
  34592. */
  34593. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34594. var boundingInfo = this.getBoundingInfo();
  34595. if (!boundingInfo) {
  34596. return false;
  34597. }
  34598. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34599. };
  34600. /**
  34601. * Renders the submesh.
  34602. * Returns it.
  34603. */
  34604. SubMesh.prototype.render = function (enableAlphaMode) {
  34605. this._renderingMesh.render(this, enableAlphaMode);
  34606. return this;
  34607. };
  34608. /**
  34609. * Returns a new Index Buffer.
  34610. * Type returned : WebGLBuffer.
  34611. */
  34612. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34613. if (!this._linesIndexBuffer) {
  34614. var linesIndices = [];
  34615. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34616. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34617. }
  34618. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34619. this.linesIndexCount = linesIndices.length;
  34620. }
  34621. return this._linesIndexBuffer;
  34622. };
  34623. /**
  34624. * True is the passed Ray intersects the submesh bounding box.
  34625. * Boolean returned.
  34626. */
  34627. SubMesh.prototype.canIntersects = function (ray) {
  34628. var boundingInfo = this.getBoundingInfo();
  34629. if (!boundingInfo) {
  34630. return false;
  34631. }
  34632. return ray.intersectsBox(boundingInfo.boundingBox);
  34633. };
  34634. /**
  34635. * Returns an object IntersectionInfo.
  34636. */
  34637. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34638. var intersectInfo = null;
  34639. var material = this.getMaterial();
  34640. if (!material) {
  34641. return null;
  34642. }
  34643. switch (material.fillMode) {
  34644. case BABYLON.Material.PointListDrawMode:
  34645. case BABYLON.Material.LineListDrawMode:
  34646. case BABYLON.Material.LineLoopDrawMode:
  34647. case BABYLON.Material.LineStripDrawMode:
  34648. case BABYLON.Material.TriangleFanDrawMode:
  34649. case BABYLON.Material.TriangleStripDrawMode:
  34650. return null;
  34651. }
  34652. // LineMesh first as it's also a Mesh...
  34653. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34654. var lineMesh = this._mesh;
  34655. // Line test
  34656. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34657. var p0 = positions[indices[index]];
  34658. var p1 = positions[indices[index + 1]];
  34659. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34660. if (length < 0) {
  34661. continue;
  34662. }
  34663. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34664. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34665. if (fastCheck) {
  34666. break;
  34667. }
  34668. }
  34669. }
  34670. }
  34671. else {
  34672. // Triangles test
  34673. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34674. var p0 = positions[indices[index]];
  34675. var p1 = positions[indices[index + 1]];
  34676. var p2 = positions[indices[index + 2]];
  34677. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34678. if (currentIntersectInfo) {
  34679. if (currentIntersectInfo.distance < 0) {
  34680. continue;
  34681. }
  34682. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34683. intersectInfo = currentIntersectInfo;
  34684. intersectInfo.faceId = index / 3;
  34685. if (fastCheck) {
  34686. break;
  34687. }
  34688. }
  34689. }
  34690. }
  34691. }
  34692. return intersectInfo;
  34693. };
  34694. SubMesh.prototype._rebuild = function () {
  34695. if (this._linesIndexBuffer) {
  34696. this._linesIndexBuffer = null;
  34697. }
  34698. };
  34699. // Clone
  34700. /**
  34701. * Creates a new Submesh from the passed Mesh.
  34702. */
  34703. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34704. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34705. if (!this.IsGlobal) {
  34706. var boundingInfo = this.getBoundingInfo();
  34707. if (!boundingInfo) {
  34708. return result;
  34709. }
  34710. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34711. }
  34712. return result;
  34713. };
  34714. // Dispose
  34715. /**
  34716. * Disposes the Submesh.
  34717. * Returns nothing.
  34718. */
  34719. SubMesh.prototype.dispose = function () {
  34720. if (this._linesIndexBuffer) {
  34721. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34722. this._linesIndexBuffer = null;
  34723. }
  34724. // Remove from mesh
  34725. var index = this._mesh.subMeshes.indexOf(this);
  34726. this._mesh.subMeshes.splice(index, 1);
  34727. };
  34728. // Statics
  34729. /**
  34730. * Creates a new Submesh from the passed parameters :
  34731. * - materialIndex (integer) : the index of the main mesh material.
  34732. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34733. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34734. * - mesh (Mesh) : the main mesh to create the submesh from.
  34735. * - renderingMesh (optional Mesh) : rendering mesh.
  34736. */
  34737. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34738. var minVertexIndex = Number.MAX_VALUE;
  34739. var maxVertexIndex = -Number.MAX_VALUE;
  34740. renderingMesh = (renderingMesh || mesh);
  34741. var indices = renderingMesh.getIndices();
  34742. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34743. var vertexIndex = indices[index];
  34744. if (vertexIndex < minVertexIndex)
  34745. minVertexIndex = vertexIndex;
  34746. if (vertexIndex > maxVertexIndex)
  34747. maxVertexIndex = vertexIndex;
  34748. }
  34749. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34750. };
  34751. return SubMesh;
  34752. }(BaseSubMesh));
  34753. BABYLON.SubMesh = SubMesh;
  34754. })(BABYLON || (BABYLON = {}));
  34755. //# sourceMappingURL=babylon.subMesh.js.map
  34756. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34757. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34758. s = arguments[i];
  34759. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34760. t[p] = s[p];
  34761. }
  34762. return t;
  34763. };
  34764. var BABYLON;
  34765. (function (BABYLON) {
  34766. /**
  34767. * Manages the defines for the Material
  34768. */
  34769. var MaterialDefines = /** @class */ (function () {
  34770. function MaterialDefines() {
  34771. this._isDirty = true;
  34772. /** @hidden */
  34773. this._areLightsDirty = true;
  34774. /** @hidden */
  34775. this._areAttributesDirty = true;
  34776. /** @hidden */
  34777. this._areTexturesDirty = true;
  34778. /** @hidden */
  34779. this._areFresnelDirty = true;
  34780. /** @hidden */
  34781. this._areMiscDirty = true;
  34782. /** @hidden */
  34783. this._areImageProcessingDirty = true;
  34784. /** @hidden */
  34785. this._normals = false;
  34786. /** @hidden */
  34787. this._uvs = false;
  34788. /** @hidden */
  34789. this._needNormals = false;
  34790. /** @hidden */
  34791. this._needUVs = false;
  34792. }
  34793. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34794. /**
  34795. * Specifies if the material needs to be re-calculated
  34796. */
  34797. get: function () {
  34798. return this._isDirty;
  34799. },
  34800. enumerable: true,
  34801. configurable: true
  34802. });
  34803. /**
  34804. * Marks the material to indicate that it has been re-calculated
  34805. */
  34806. MaterialDefines.prototype.markAsProcessed = function () {
  34807. this._isDirty = false;
  34808. this._areAttributesDirty = false;
  34809. this._areTexturesDirty = false;
  34810. this._areFresnelDirty = false;
  34811. this._areLightsDirty = false;
  34812. this._areMiscDirty = false;
  34813. this._areImageProcessingDirty = false;
  34814. };
  34815. /**
  34816. * Marks the material to indicate that it needs to be re-calculated
  34817. */
  34818. MaterialDefines.prototype.markAsUnprocessed = function () {
  34819. this._isDirty = true;
  34820. };
  34821. /**
  34822. * Marks the material to indicate all of its defines need to be re-calculated
  34823. */
  34824. MaterialDefines.prototype.markAllAsDirty = function () {
  34825. this._areTexturesDirty = true;
  34826. this._areAttributesDirty = true;
  34827. this._areLightsDirty = true;
  34828. this._areFresnelDirty = true;
  34829. this._areMiscDirty = true;
  34830. this._areImageProcessingDirty = true;
  34831. this._isDirty = true;
  34832. };
  34833. /**
  34834. * Marks the material to indicate that image processing needs to be re-calculated
  34835. */
  34836. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34837. this._areImageProcessingDirty = true;
  34838. this._isDirty = true;
  34839. };
  34840. /**
  34841. * Marks the material to indicate the lights need to be re-calculated
  34842. */
  34843. MaterialDefines.prototype.markAsLightDirty = function () {
  34844. this._areLightsDirty = true;
  34845. this._isDirty = true;
  34846. };
  34847. /**
  34848. * Marks the attribute state as changed
  34849. */
  34850. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34851. this._areAttributesDirty = true;
  34852. this._isDirty = true;
  34853. };
  34854. /**
  34855. * Marks the texture state as changed
  34856. */
  34857. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34858. this._areTexturesDirty = true;
  34859. this._isDirty = true;
  34860. };
  34861. /**
  34862. * Marks the fresnel state as changed
  34863. */
  34864. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34865. this._areFresnelDirty = true;
  34866. this._isDirty = true;
  34867. };
  34868. /**
  34869. * Marks the misc state as changed
  34870. */
  34871. MaterialDefines.prototype.markAsMiscDirty = function () {
  34872. this._areMiscDirty = true;
  34873. this._isDirty = true;
  34874. };
  34875. /**
  34876. * Rebuilds the material defines
  34877. */
  34878. MaterialDefines.prototype.rebuild = function () {
  34879. if (this._keys) {
  34880. delete this._keys;
  34881. }
  34882. this._keys = [];
  34883. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34884. var key = _a[_i];
  34885. if (key[0] === "_") {
  34886. continue;
  34887. }
  34888. this._keys.push(key);
  34889. }
  34890. };
  34891. /**
  34892. * Specifies if two material defines are equal
  34893. * @param other - A material define instance to compare to
  34894. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34895. */
  34896. MaterialDefines.prototype.isEqual = function (other) {
  34897. if (this._keys.length !== other._keys.length) {
  34898. return false;
  34899. }
  34900. for (var index = 0; index < this._keys.length; index++) {
  34901. var prop = this._keys[index];
  34902. if (this[prop] !== other[prop]) {
  34903. return false;
  34904. }
  34905. }
  34906. return true;
  34907. };
  34908. /**
  34909. * Clones this instance's defines to another instance
  34910. * @param other - material defines to clone values to
  34911. */
  34912. MaterialDefines.prototype.cloneTo = function (other) {
  34913. if (this._keys.length !== other._keys.length) {
  34914. other._keys = this._keys.slice(0);
  34915. }
  34916. for (var index = 0; index < this._keys.length; index++) {
  34917. var prop = this._keys[index];
  34918. other[prop] = this[prop];
  34919. }
  34920. };
  34921. /**
  34922. * Resets the material define values
  34923. */
  34924. MaterialDefines.prototype.reset = function () {
  34925. for (var index = 0; index < this._keys.length; index++) {
  34926. var prop = this._keys[index];
  34927. var type = typeof this[prop];
  34928. switch (type) {
  34929. case "number":
  34930. this[prop] = 0;
  34931. break;
  34932. case "string":
  34933. this[prop] = "";
  34934. break;
  34935. default:
  34936. this[prop] = false;
  34937. break;
  34938. }
  34939. }
  34940. };
  34941. /**
  34942. * Converts the material define values to a string
  34943. * @returns - String of material define information
  34944. */
  34945. MaterialDefines.prototype.toString = function () {
  34946. var result = "";
  34947. for (var index = 0; index < this._keys.length; index++) {
  34948. var prop = this._keys[index];
  34949. var value = this[prop];
  34950. var type = typeof value;
  34951. switch (type) {
  34952. case "number":
  34953. case "string":
  34954. result += "#define " + prop + " " + value + "\n";
  34955. break;
  34956. default:
  34957. if (value) {
  34958. result += "#define " + prop + "\n";
  34959. }
  34960. break;
  34961. }
  34962. }
  34963. return result;
  34964. };
  34965. return MaterialDefines;
  34966. }());
  34967. BABYLON.MaterialDefines = MaterialDefines;
  34968. /**
  34969. * Base class for the main features of a material in Babylon.js
  34970. */
  34971. var Material = /** @class */ (function () {
  34972. /**
  34973. * Creates a material instance
  34974. * @param name defines the name of the material
  34975. * @param scene defines the scene to reference
  34976. * @param doNotAdd specifies if the material should be added to the scene
  34977. */
  34978. function Material(name, scene, doNotAdd) {
  34979. /**
  34980. * Specifies if the ready state should be checked on each call
  34981. */
  34982. this.checkReadyOnEveryCall = false;
  34983. /**
  34984. * Specifies if the ready state should be checked once
  34985. */
  34986. this.checkReadyOnlyOnce = false;
  34987. /**
  34988. * The state of the material
  34989. */
  34990. this.state = "";
  34991. /**
  34992. * The alpha value of the material
  34993. */
  34994. this._alpha = 1.0;
  34995. /**
  34996. * Specifies if back face culling is enabled
  34997. */
  34998. this._backFaceCulling = true;
  34999. /**
  35000. * Specifies if the material should be serialized
  35001. */
  35002. this.doNotSerialize = false;
  35003. /**
  35004. * Specifies if the effect should be stored on sub meshes
  35005. */
  35006. this.storeEffectOnSubMeshes = false;
  35007. /**
  35008. * An event triggered when the material is disposed
  35009. */
  35010. this.onDisposeObservable = new BABYLON.Observable();
  35011. /**
  35012. * An event triggered when the material is bound
  35013. */
  35014. this.onBindObservable = new BABYLON.Observable();
  35015. /**
  35016. * An event triggered when the material is unbound
  35017. */
  35018. this.onUnBindObservable = new BABYLON.Observable();
  35019. /**
  35020. * Stores the value of the alpha mode
  35021. */
  35022. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35023. /**
  35024. * Stores the state of the need depth pre-pass value
  35025. */
  35026. this._needDepthPrePass = false;
  35027. /**
  35028. * Specifies if depth writing should be disabled
  35029. */
  35030. this.disableDepthWrite = false;
  35031. /**
  35032. * Specifies if depth writing should be forced
  35033. */
  35034. this.forceDepthWrite = false;
  35035. /**
  35036. * Specifies if there should be a separate pass for culling
  35037. */
  35038. this.separateCullingPass = false;
  35039. /**
  35040. * Stores the state specifing if fog should be enabled
  35041. */
  35042. this._fogEnabled = true;
  35043. /**
  35044. * Stores the size of points
  35045. */
  35046. this.pointSize = 1.0;
  35047. /**
  35048. * Stores the z offset value
  35049. */
  35050. this.zOffset = 0;
  35051. /**
  35052. * Specifies if the material was previously ready
  35053. */
  35054. this._wasPreviouslyReady = false;
  35055. /**
  35056. * Stores the fill mode state
  35057. */
  35058. this._fillMode = Material.TriangleFillMode;
  35059. this.name = name;
  35060. this.id = name || BABYLON.Tools.RandomId();
  35061. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35062. this.uniqueId = this._scene.getUniqueId();
  35063. if (this._scene.useRightHandedSystem) {
  35064. this.sideOrientation = Material.ClockWiseSideOrientation;
  35065. }
  35066. else {
  35067. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35068. }
  35069. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35070. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35071. if (!doNotAdd) {
  35072. this._scene.materials.push(this);
  35073. }
  35074. }
  35075. Object.defineProperty(Material, "TriangleFillMode", {
  35076. /**
  35077. * Returns the triangle fill mode
  35078. */
  35079. get: function () {
  35080. return Material._TriangleFillMode;
  35081. },
  35082. enumerable: true,
  35083. configurable: true
  35084. });
  35085. Object.defineProperty(Material, "WireFrameFillMode", {
  35086. /**
  35087. * Returns the wireframe mode
  35088. */
  35089. get: function () {
  35090. return Material._WireFrameFillMode;
  35091. },
  35092. enumerable: true,
  35093. configurable: true
  35094. });
  35095. Object.defineProperty(Material, "PointFillMode", {
  35096. /**
  35097. * Returns the point fill mode
  35098. */
  35099. get: function () {
  35100. return Material._PointFillMode;
  35101. },
  35102. enumerable: true,
  35103. configurable: true
  35104. });
  35105. Object.defineProperty(Material, "PointListDrawMode", {
  35106. /**
  35107. * Returns the point list draw mode
  35108. */
  35109. get: function () {
  35110. return Material._PointListDrawMode;
  35111. },
  35112. enumerable: true,
  35113. configurable: true
  35114. });
  35115. Object.defineProperty(Material, "LineListDrawMode", {
  35116. /**
  35117. * Returns the line list draw mode
  35118. */
  35119. get: function () {
  35120. return Material._LineListDrawMode;
  35121. },
  35122. enumerable: true,
  35123. configurable: true
  35124. });
  35125. Object.defineProperty(Material, "LineLoopDrawMode", {
  35126. /**
  35127. * Returns the line loop draw mode
  35128. */
  35129. get: function () {
  35130. return Material._LineLoopDrawMode;
  35131. },
  35132. enumerable: true,
  35133. configurable: true
  35134. });
  35135. Object.defineProperty(Material, "LineStripDrawMode", {
  35136. /**
  35137. * Returns the line strip draw mode
  35138. */
  35139. get: function () {
  35140. return Material._LineStripDrawMode;
  35141. },
  35142. enumerable: true,
  35143. configurable: true
  35144. });
  35145. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35146. /**
  35147. * Returns the triangle strip draw mode
  35148. */
  35149. get: function () {
  35150. return Material._TriangleStripDrawMode;
  35151. },
  35152. enumerable: true,
  35153. configurable: true
  35154. });
  35155. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35156. /**
  35157. * Returns the triangle fan draw mode
  35158. */
  35159. get: function () {
  35160. return Material._TriangleFanDrawMode;
  35161. },
  35162. enumerable: true,
  35163. configurable: true
  35164. });
  35165. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35166. /**
  35167. * Returns the clock-wise side orientation
  35168. */
  35169. get: function () {
  35170. return Material._ClockWiseSideOrientation;
  35171. },
  35172. enumerable: true,
  35173. configurable: true
  35174. });
  35175. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35176. /**
  35177. * Returns the counter clock-wise side orientation
  35178. */
  35179. get: function () {
  35180. return Material._CounterClockWiseSideOrientation;
  35181. },
  35182. enumerable: true,
  35183. configurable: true
  35184. });
  35185. Object.defineProperty(Material, "TextureDirtyFlag", {
  35186. /**
  35187. * Returns the dirty texture flag value
  35188. */
  35189. get: function () {
  35190. return Material._TextureDirtyFlag;
  35191. },
  35192. enumerable: true,
  35193. configurable: true
  35194. });
  35195. Object.defineProperty(Material, "LightDirtyFlag", {
  35196. /**
  35197. * Returns the dirty light flag value
  35198. */
  35199. get: function () {
  35200. return Material._LightDirtyFlag;
  35201. },
  35202. enumerable: true,
  35203. configurable: true
  35204. });
  35205. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35206. /**
  35207. * Returns the dirty fresnel flag value
  35208. */
  35209. get: function () {
  35210. return Material._FresnelDirtyFlag;
  35211. },
  35212. enumerable: true,
  35213. configurable: true
  35214. });
  35215. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35216. /**
  35217. * Returns the dirty attributes flag value
  35218. */
  35219. get: function () {
  35220. return Material._AttributesDirtyFlag;
  35221. },
  35222. enumerable: true,
  35223. configurable: true
  35224. });
  35225. Object.defineProperty(Material, "MiscDirtyFlag", {
  35226. /**
  35227. * Returns the dirty misc flag value
  35228. */
  35229. get: function () {
  35230. return Material._MiscDirtyFlag;
  35231. },
  35232. enumerable: true,
  35233. configurable: true
  35234. });
  35235. Object.defineProperty(Material.prototype, "alpha", {
  35236. /**
  35237. * Gets the alpha value of the material
  35238. */
  35239. get: function () {
  35240. return this._alpha;
  35241. },
  35242. /**
  35243. * Sets the alpha value of the material
  35244. */
  35245. set: function (value) {
  35246. if (this._alpha === value) {
  35247. return;
  35248. }
  35249. this._alpha = value;
  35250. this.markAsDirty(Material.MiscDirtyFlag);
  35251. },
  35252. enumerable: true,
  35253. configurable: true
  35254. });
  35255. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35256. /**
  35257. * Gets the back-face culling state
  35258. */
  35259. get: function () {
  35260. return this._backFaceCulling;
  35261. },
  35262. /**
  35263. * Sets the back-face culling state
  35264. */
  35265. set: function (value) {
  35266. if (this._backFaceCulling === value) {
  35267. return;
  35268. }
  35269. this._backFaceCulling = value;
  35270. this.markAsDirty(Material.TextureDirtyFlag);
  35271. },
  35272. enumerable: true,
  35273. configurable: true
  35274. });
  35275. Object.defineProperty(Material.prototype, "onDispose", {
  35276. /**
  35277. * Called during a dispose event
  35278. */
  35279. set: function (callback) {
  35280. if (this._onDisposeObserver) {
  35281. this.onDisposeObservable.remove(this._onDisposeObserver);
  35282. }
  35283. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35284. },
  35285. enumerable: true,
  35286. configurable: true
  35287. });
  35288. Object.defineProperty(Material.prototype, "onBind", {
  35289. /**
  35290. * Called during a bind event
  35291. */
  35292. set: function (callback) {
  35293. if (this._onBindObserver) {
  35294. this.onBindObservable.remove(this._onBindObserver);
  35295. }
  35296. this._onBindObserver = this.onBindObservable.add(callback);
  35297. },
  35298. enumerable: true,
  35299. configurable: true
  35300. });
  35301. Object.defineProperty(Material.prototype, "alphaMode", {
  35302. /**
  35303. * Gets the value of the alpha mode
  35304. */
  35305. get: function () {
  35306. return this._alphaMode;
  35307. },
  35308. /**
  35309. * Sets the value of the alpha mode.
  35310. *
  35311. * | Value | Type | Description |
  35312. * | --- | --- | --- |
  35313. * | 0 | ALPHA_DISABLE | |
  35314. * | 1 | ALPHA_ADD | |
  35315. * | 2 | ALPHA_COMBINE | |
  35316. * | 3 | ALPHA_SUBTRACT | |
  35317. * | 4 | ALPHA_MULTIPLY | |
  35318. * | 5 | ALPHA_MAXIMIZED | |
  35319. * | 6 | ALPHA_ONEONE | |
  35320. * | 7 | ALPHA_PREMULTIPLIED | |
  35321. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35322. * | 9 | ALPHA_INTERPOLATE | |
  35323. * | 10 | ALPHA_SCREENMODE | |
  35324. *
  35325. */
  35326. set: function (value) {
  35327. if (this._alphaMode === value) {
  35328. return;
  35329. }
  35330. this._alphaMode = value;
  35331. this.markAsDirty(Material.TextureDirtyFlag);
  35332. },
  35333. enumerable: true,
  35334. configurable: true
  35335. });
  35336. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35337. /**
  35338. * Gets the depth pre-pass value
  35339. */
  35340. get: function () {
  35341. return this._needDepthPrePass;
  35342. },
  35343. /**
  35344. * Sets the need depth pre-pass value
  35345. */
  35346. set: function (value) {
  35347. if (this._needDepthPrePass === value) {
  35348. return;
  35349. }
  35350. this._needDepthPrePass = value;
  35351. if (this._needDepthPrePass) {
  35352. this.checkReadyOnEveryCall = true;
  35353. }
  35354. },
  35355. enumerable: true,
  35356. configurable: true
  35357. });
  35358. Object.defineProperty(Material.prototype, "fogEnabled", {
  35359. /**
  35360. * Gets the value of the fog enabled state
  35361. */
  35362. get: function () {
  35363. return this._fogEnabled;
  35364. },
  35365. /**
  35366. * Sets the state for enabling fog
  35367. */
  35368. set: function (value) {
  35369. if (this._fogEnabled === value) {
  35370. return;
  35371. }
  35372. this._fogEnabled = value;
  35373. this.markAsDirty(Material.MiscDirtyFlag);
  35374. },
  35375. enumerable: true,
  35376. configurable: true
  35377. });
  35378. Object.defineProperty(Material.prototype, "wireframe", {
  35379. /**
  35380. * Gets a value specifying if wireframe mode is enabled
  35381. */
  35382. get: function () {
  35383. switch (this._fillMode) {
  35384. case Material.WireFrameFillMode:
  35385. case Material.LineListDrawMode:
  35386. case Material.LineLoopDrawMode:
  35387. case Material.LineStripDrawMode:
  35388. return true;
  35389. }
  35390. return this._scene.forceWireframe;
  35391. },
  35392. /**
  35393. * Sets the state of wireframe mode
  35394. */
  35395. set: function (value) {
  35396. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35397. },
  35398. enumerable: true,
  35399. configurable: true
  35400. });
  35401. Object.defineProperty(Material.prototype, "pointsCloud", {
  35402. /**
  35403. * Gets the value specifying if point clouds are enabled
  35404. */
  35405. get: function () {
  35406. switch (this._fillMode) {
  35407. case Material.PointFillMode:
  35408. case Material.PointListDrawMode:
  35409. return true;
  35410. }
  35411. return this._scene.forcePointsCloud;
  35412. },
  35413. /**
  35414. * Sets the state of point cloud mode
  35415. */
  35416. set: function (value) {
  35417. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35418. },
  35419. enumerable: true,
  35420. configurable: true
  35421. });
  35422. Object.defineProperty(Material.prototype, "fillMode", {
  35423. /**
  35424. * Gets the material fill mode
  35425. */
  35426. get: function () {
  35427. return this._fillMode;
  35428. },
  35429. /**
  35430. * Sets the material fill mode
  35431. */
  35432. set: function (value) {
  35433. if (this._fillMode === value) {
  35434. return;
  35435. }
  35436. this._fillMode = value;
  35437. this.markAsDirty(Material.MiscDirtyFlag);
  35438. },
  35439. enumerable: true,
  35440. configurable: true
  35441. });
  35442. /**
  35443. * Returns a string representation of the current material
  35444. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35445. * @returns a string with material information
  35446. */
  35447. Material.prototype.toString = function (fullDetails) {
  35448. var ret = "Name: " + this.name;
  35449. if (fullDetails) {
  35450. }
  35451. return ret;
  35452. };
  35453. /**
  35454. * Gets the class name of the material
  35455. * @returns a string with the class name of the material
  35456. */
  35457. Material.prototype.getClassName = function () {
  35458. return "Material";
  35459. };
  35460. Object.defineProperty(Material.prototype, "isFrozen", {
  35461. /**
  35462. * Specifies if updates for the material been locked
  35463. */
  35464. get: function () {
  35465. return this.checkReadyOnlyOnce;
  35466. },
  35467. enumerable: true,
  35468. configurable: true
  35469. });
  35470. /**
  35471. * Locks updates for the material
  35472. */
  35473. Material.prototype.freeze = function () {
  35474. this.checkReadyOnlyOnce = true;
  35475. };
  35476. /**
  35477. * Unlocks updates for the material
  35478. */
  35479. Material.prototype.unfreeze = function () {
  35480. this.checkReadyOnlyOnce = false;
  35481. };
  35482. /**
  35483. * Specifies if the material is ready to be used
  35484. * @param mesh defines the mesh to check
  35485. * @param useInstances specifies if instances should be used
  35486. * @returns a boolean indicating if the material is ready to be used
  35487. */
  35488. Material.prototype.isReady = function (mesh, useInstances) {
  35489. return true;
  35490. };
  35491. /**
  35492. * Specifies that the submesh is ready to be used
  35493. * @param mesh defines the mesh to check
  35494. * @param subMesh defines which submesh to check
  35495. * @param useInstances specifies that instances should be used
  35496. * @returns a boolean indicating that the submesh is ready or not
  35497. */
  35498. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35499. return false;
  35500. };
  35501. /**
  35502. * Returns the material effect
  35503. * @returns the effect associated with the material
  35504. */
  35505. Material.prototype.getEffect = function () {
  35506. return this._effect;
  35507. };
  35508. /**
  35509. * Returns the current scene
  35510. * @returns a Scene
  35511. */
  35512. Material.prototype.getScene = function () {
  35513. return this._scene;
  35514. };
  35515. /**
  35516. * Specifies if the material will require alpha blending
  35517. * @returns a boolean specifying if alpha blending is needed
  35518. */
  35519. Material.prototype.needAlphaBlending = function () {
  35520. return (this.alpha < 1.0);
  35521. };
  35522. /**
  35523. * Specifies if the mesh will require alpha blending
  35524. * @param mesh defines the mesh to check
  35525. * @returns a boolean specifying if alpha blending is needed for the mesh
  35526. */
  35527. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35528. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35529. };
  35530. /**
  35531. * Specifies if this material should be rendered in alpha test mode
  35532. * @returns a boolean specifying if an alpha test is needed.
  35533. */
  35534. Material.prototype.needAlphaTesting = function () {
  35535. return false;
  35536. };
  35537. /**
  35538. * Gets the texture used for the alpha test
  35539. * @returns the texture to use for alpha testing
  35540. */
  35541. Material.prototype.getAlphaTestTexture = function () {
  35542. return null;
  35543. };
  35544. /**
  35545. * Marks the material to indicate that it needs to be re-calculated
  35546. */
  35547. Material.prototype.markDirty = function () {
  35548. this._wasPreviouslyReady = false;
  35549. };
  35550. /** @hidden */
  35551. Material.prototype._preBind = function (effect, overrideOrientation) {
  35552. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35553. var engine = this._scene.getEngine();
  35554. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35555. var reverse = orientation === Material.ClockWiseSideOrientation;
  35556. engine.enableEffect(effect ? effect : this._effect);
  35557. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35558. return reverse;
  35559. };
  35560. /**
  35561. * Binds the material to the mesh
  35562. * @param world defines the world transformation matrix
  35563. * @param mesh defines the mesh to bind the material to
  35564. */
  35565. Material.prototype.bind = function (world, mesh) {
  35566. };
  35567. /**
  35568. * Binds the submesh to the material
  35569. * @param world defines the world transformation matrix
  35570. * @param mesh defines the mesh containing the submesh
  35571. * @param subMesh defines the submesh to bind the material to
  35572. */
  35573. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35574. };
  35575. /**
  35576. * Binds the world matrix to the material
  35577. * @param world defines the world transformation matrix
  35578. */
  35579. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35580. };
  35581. /**
  35582. * Binds the scene's uniform buffer to the effect.
  35583. * @param effect defines the effect to bind to the scene uniform buffer
  35584. * @param sceneUbo defines the uniform buffer storing scene data
  35585. */
  35586. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35587. sceneUbo.bindToEffect(effect, "Scene");
  35588. };
  35589. /**
  35590. * Binds the view matrix to the effect
  35591. * @param effect defines the effect to bind the view matrix to
  35592. */
  35593. Material.prototype.bindView = function (effect) {
  35594. if (!this._useUBO) {
  35595. effect.setMatrix("view", this.getScene().getViewMatrix());
  35596. }
  35597. else {
  35598. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35599. }
  35600. };
  35601. /**
  35602. * Binds the view projection matrix to the effect
  35603. * @param effect defines the effect to bind the view projection matrix to
  35604. */
  35605. Material.prototype.bindViewProjection = function (effect) {
  35606. if (!this._useUBO) {
  35607. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35608. }
  35609. else {
  35610. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35611. }
  35612. };
  35613. /**
  35614. * Specifies if material alpha testing should be turned on for the mesh
  35615. * @param mesh defines the mesh to check
  35616. */
  35617. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35618. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35619. };
  35620. /**
  35621. * Processes to execute after binding the material to a mesh
  35622. * @param mesh defines the rendered mesh
  35623. */
  35624. Material.prototype._afterBind = function (mesh) {
  35625. this._scene._cachedMaterial = this;
  35626. if (mesh) {
  35627. this._scene._cachedVisibility = mesh.visibility;
  35628. }
  35629. else {
  35630. this._scene._cachedVisibility = 1;
  35631. }
  35632. if (mesh) {
  35633. this.onBindObservable.notifyObservers(mesh);
  35634. }
  35635. if (this.disableDepthWrite) {
  35636. var engine = this._scene.getEngine();
  35637. this._cachedDepthWriteState = engine.getDepthWrite();
  35638. engine.setDepthWrite(false);
  35639. }
  35640. };
  35641. /**
  35642. * Unbinds the material from the mesh
  35643. */
  35644. Material.prototype.unbind = function () {
  35645. this.onUnBindObservable.notifyObservers(this);
  35646. if (this.disableDepthWrite) {
  35647. var engine = this._scene.getEngine();
  35648. engine.setDepthWrite(this._cachedDepthWriteState);
  35649. }
  35650. };
  35651. /**
  35652. * Gets the active textures from the material
  35653. * @returns an array of textures
  35654. */
  35655. Material.prototype.getActiveTextures = function () {
  35656. return [];
  35657. };
  35658. /**
  35659. * Specifies if the material uses a texture
  35660. * @param texture defines the texture to check against the material
  35661. * @returns a boolean specifying if the material uses the texture
  35662. */
  35663. Material.prototype.hasTexture = function (texture) {
  35664. return false;
  35665. };
  35666. /**
  35667. * Makes a duplicate of the material, and gives it a new name
  35668. * @param name defines the new name for the duplicated material
  35669. * @returns the cloned material
  35670. */
  35671. Material.prototype.clone = function (name) {
  35672. return null;
  35673. };
  35674. /**
  35675. * Gets the meshes bound to the material
  35676. * @returns an array of meshes bound to the material
  35677. */
  35678. Material.prototype.getBindedMeshes = function () {
  35679. var result = new Array();
  35680. for (var index = 0; index < this._scene.meshes.length; index++) {
  35681. var mesh = this._scene.meshes[index];
  35682. if (mesh.material === this) {
  35683. result.push(mesh);
  35684. }
  35685. }
  35686. return result;
  35687. };
  35688. /**
  35689. * Force shader compilation
  35690. * @param mesh defines the mesh associated with this material
  35691. * @param onCompiled defines a function to execute once the material is compiled
  35692. * @param options defines the options to configure the compilation
  35693. */
  35694. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35695. var _this = this;
  35696. var localOptions = __assign({ clipPlane: false }, options);
  35697. var subMesh = new BABYLON.BaseSubMesh();
  35698. var scene = this.getScene();
  35699. var checkReady = function () {
  35700. if (!_this._scene || !_this._scene.getEngine()) {
  35701. return;
  35702. }
  35703. if (subMesh._materialDefines) {
  35704. subMesh._materialDefines._renderId = -1;
  35705. }
  35706. var clipPlaneState = scene.clipPlane;
  35707. if (localOptions.clipPlane) {
  35708. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35709. }
  35710. if (_this.storeEffectOnSubMeshes) {
  35711. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35712. if (onCompiled) {
  35713. onCompiled(_this);
  35714. }
  35715. }
  35716. else {
  35717. setTimeout(checkReady, 16);
  35718. }
  35719. }
  35720. else {
  35721. if (_this.isReady(mesh)) {
  35722. if (onCompiled) {
  35723. onCompiled(_this);
  35724. }
  35725. }
  35726. else {
  35727. setTimeout(checkReady, 16);
  35728. }
  35729. }
  35730. if (localOptions.clipPlane) {
  35731. scene.clipPlane = clipPlaneState;
  35732. }
  35733. };
  35734. checkReady();
  35735. };
  35736. /**
  35737. * Force shader compilation
  35738. * @param mesh defines the mesh that will use this material
  35739. * @param options defines additional options for compiling the shaders
  35740. * @returns a promise that resolves when the compilation completes
  35741. */
  35742. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35743. var _this = this;
  35744. return new Promise(function (resolve) {
  35745. _this.forceCompilation(mesh, function () {
  35746. resolve();
  35747. }, options);
  35748. });
  35749. };
  35750. /**
  35751. * Marks a define in the material to indicate that it needs to be re-computed
  35752. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35753. */
  35754. Material.prototype.markAsDirty = function (flag) {
  35755. if (flag & Material.TextureDirtyFlag) {
  35756. this._markAllSubMeshesAsTexturesDirty();
  35757. }
  35758. if (flag & Material.LightDirtyFlag) {
  35759. this._markAllSubMeshesAsLightsDirty();
  35760. }
  35761. if (flag & Material.FresnelDirtyFlag) {
  35762. this._markAllSubMeshesAsFresnelDirty();
  35763. }
  35764. if (flag & Material.AttributesDirtyFlag) {
  35765. this._markAllSubMeshesAsAttributesDirty();
  35766. }
  35767. if (flag & Material.MiscDirtyFlag) {
  35768. this._markAllSubMeshesAsMiscDirty();
  35769. }
  35770. this.getScene().resetCachedMaterial();
  35771. };
  35772. /**
  35773. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35774. * @param func defines a function which checks material defines against the submeshes
  35775. */
  35776. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35777. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35778. var mesh = _a[_i];
  35779. if (!mesh.subMeshes) {
  35780. continue;
  35781. }
  35782. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35783. var subMesh = _c[_b];
  35784. if (subMesh.getMaterial() !== this) {
  35785. continue;
  35786. }
  35787. if (!subMesh._materialDefines) {
  35788. continue;
  35789. }
  35790. func(subMesh._materialDefines);
  35791. }
  35792. }
  35793. };
  35794. /**
  35795. * Indicates that image processing needs to be re-calculated for all submeshes
  35796. */
  35797. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35798. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35799. };
  35800. /**
  35801. * Indicates that textures need to be re-calculated for all submeshes
  35802. */
  35803. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35804. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35805. };
  35806. /**
  35807. * Indicates that fresnel needs to be re-calculated for all submeshes
  35808. */
  35809. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35810. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35811. };
  35812. /**
  35813. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35814. */
  35815. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35816. this._markAllSubMeshesAsDirty(function (defines) {
  35817. defines.markAsFresnelDirty();
  35818. defines.markAsMiscDirty();
  35819. });
  35820. };
  35821. /**
  35822. * Indicates that lights need to be re-calculated for all submeshes
  35823. */
  35824. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35825. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35826. };
  35827. /**
  35828. * Indicates that attributes need to be re-calculated for all submeshes
  35829. */
  35830. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35831. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35832. };
  35833. /**
  35834. * Indicates that misc needs to be re-calculated for all submeshes
  35835. */
  35836. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35837. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35838. };
  35839. /**
  35840. * Indicates that textures and misc need to be re-calculated for all submeshes
  35841. */
  35842. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35843. this._markAllSubMeshesAsDirty(function (defines) {
  35844. defines.markAsTexturesDirty();
  35845. defines.markAsMiscDirty();
  35846. });
  35847. };
  35848. /**
  35849. * Disposes the material
  35850. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35851. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35852. */
  35853. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35854. // Animations
  35855. this.getScene().stopAnimation(this);
  35856. this.getScene().freeProcessedMaterials();
  35857. // Remove from scene
  35858. var index = this._scene.materials.indexOf(this);
  35859. if (index >= 0) {
  35860. this._scene.materials.splice(index, 1);
  35861. }
  35862. // Remove from meshes
  35863. for (index = 0; index < this._scene.meshes.length; index++) {
  35864. var mesh = this._scene.meshes[index];
  35865. if (mesh.material === this) {
  35866. mesh.material = null;
  35867. if (mesh.geometry) {
  35868. var geometry = (mesh.geometry);
  35869. if (this.storeEffectOnSubMeshes) {
  35870. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35871. var subMesh = _a[_i];
  35872. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35873. if (forceDisposeEffect && subMesh._materialEffect) {
  35874. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35875. }
  35876. }
  35877. }
  35878. else {
  35879. geometry._releaseVertexArrayObject(this._effect);
  35880. }
  35881. }
  35882. }
  35883. }
  35884. this._uniformBuffer.dispose();
  35885. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35886. if (forceDisposeEffect && this._effect) {
  35887. if (!this.storeEffectOnSubMeshes) {
  35888. this._scene.getEngine()._releaseEffect(this._effect);
  35889. }
  35890. this._effect = null;
  35891. }
  35892. // Callback
  35893. this.onDisposeObservable.notifyObservers(this);
  35894. this.onDisposeObservable.clear();
  35895. this.onBindObservable.clear();
  35896. this.onUnBindObservable.clear();
  35897. };
  35898. /**
  35899. * Serializes this material
  35900. * @returns the serialized material object
  35901. */
  35902. Material.prototype.serialize = function () {
  35903. return BABYLON.SerializationHelper.Serialize(this);
  35904. };
  35905. /**
  35906. * Creates a MultiMaterial from parsed MultiMaterial data.
  35907. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35908. * @param scene defines the hosting scene
  35909. * @returns a new MultiMaterial
  35910. */
  35911. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35912. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35913. multiMaterial.id = parsedMultiMaterial.id;
  35914. if (BABYLON.Tags) {
  35915. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35916. }
  35917. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35918. var subMatId = parsedMultiMaterial.materials[matIndex];
  35919. if (subMatId) {
  35920. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35921. }
  35922. else {
  35923. multiMaterial.subMaterials.push(null);
  35924. }
  35925. }
  35926. return multiMaterial;
  35927. };
  35928. /**
  35929. * Creates a material from parsed material data
  35930. * @param parsedMaterial defines parsed material data
  35931. * @param scene defines the hosting scene
  35932. * @param rootUrl defines the root URL to use to load textures
  35933. * @returns a new material
  35934. */
  35935. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35936. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35937. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35938. }
  35939. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35940. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35941. if (!BABYLON.LegacyPBRMaterial) {
  35942. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35943. return;
  35944. }
  35945. }
  35946. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35947. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35948. };
  35949. // Triangle views
  35950. Material._TriangleFillMode = 0;
  35951. Material._WireFrameFillMode = 1;
  35952. Material._PointFillMode = 2;
  35953. // Draw modes
  35954. Material._PointListDrawMode = 3;
  35955. Material._LineListDrawMode = 4;
  35956. Material._LineLoopDrawMode = 5;
  35957. Material._LineStripDrawMode = 6;
  35958. Material._TriangleStripDrawMode = 7;
  35959. Material._TriangleFanDrawMode = 8;
  35960. /**
  35961. * Stores the clock-wise side orientation
  35962. */
  35963. Material._ClockWiseSideOrientation = 0;
  35964. /**
  35965. * Stores the counter clock-wise side orientation
  35966. */
  35967. Material._CounterClockWiseSideOrientation = 1;
  35968. /**
  35969. * The dirty texture flag value
  35970. */
  35971. Material._TextureDirtyFlag = 1;
  35972. /**
  35973. * The dirty light flag value
  35974. */
  35975. Material._LightDirtyFlag = 2;
  35976. /**
  35977. * The dirty fresnel flag value
  35978. */
  35979. Material._FresnelDirtyFlag = 4;
  35980. /**
  35981. * The dirty attribute flag value
  35982. */
  35983. Material._AttributesDirtyFlag = 8;
  35984. /**
  35985. * The dirty misc flag value
  35986. */
  35987. Material._MiscDirtyFlag = 16;
  35988. __decorate([
  35989. BABYLON.serialize()
  35990. ], Material.prototype, "id", void 0);
  35991. __decorate([
  35992. BABYLON.serialize()
  35993. ], Material.prototype, "uniqueId", void 0);
  35994. __decorate([
  35995. BABYLON.serialize()
  35996. ], Material.prototype, "name", void 0);
  35997. __decorate([
  35998. BABYLON.serialize()
  35999. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36000. __decorate([
  36001. BABYLON.serialize()
  36002. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36003. __decorate([
  36004. BABYLON.serialize()
  36005. ], Material.prototype, "state", void 0);
  36006. __decorate([
  36007. BABYLON.serialize("alpha")
  36008. ], Material.prototype, "_alpha", void 0);
  36009. __decorate([
  36010. BABYLON.serialize("backFaceCulling")
  36011. ], Material.prototype, "_backFaceCulling", void 0);
  36012. __decorate([
  36013. BABYLON.serialize()
  36014. ], Material.prototype, "sideOrientation", void 0);
  36015. __decorate([
  36016. BABYLON.serialize("alphaMode")
  36017. ], Material.prototype, "_alphaMode", void 0);
  36018. __decorate([
  36019. BABYLON.serialize()
  36020. ], Material.prototype, "_needDepthPrePass", void 0);
  36021. __decorate([
  36022. BABYLON.serialize()
  36023. ], Material.prototype, "disableDepthWrite", void 0);
  36024. __decorate([
  36025. BABYLON.serialize()
  36026. ], Material.prototype, "forceDepthWrite", void 0);
  36027. __decorate([
  36028. BABYLON.serialize()
  36029. ], Material.prototype, "separateCullingPass", void 0);
  36030. __decorate([
  36031. BABYLON.serialize("fogEnabled")
  36032. ], Material.prototype, "_fogEnabled", void 0);
  36033. __decorate([
  36034. BABYLON.serialize()
  36035. ], Material.prototype, "pointSize", void 0);
  36036. __decorate([
  36037. BABYLON.serialize()
  36038. ], Material.prototype, "zOffset", void 0);
  36039. __decorate([
  36040. BABYLON.serialize()
  36041. ], Material.prototype, "wireframe", null);
  36042. __decorate([
  36043. BABYLON.serialize()
  36044. ], Material.prototype, "pointsCloud", null);
  36045. __decorate([
  36046. BABYLON.serialize()
  36047. ], Material.prototype, "fillMode", null);
  36048. return Material;
  36049. }());
  36050. BABYLON.Material = Material;
  36051. })(BABYLON || (BABYLON = {}));
  36052. //# sourceMappingURL=babylon.material.js.map
  36053. var BABYLON;
  36054. (function (BABYLON) {
  36055. var UniformBuffer = /** @class */ (function () {
  36056. /**
  36057. * Uniform buffer objects.
  36058. *
  36059. * Handles blocks of uniform on the GPU.
  36060. *
  36061. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36062. *
  36063. * For more information, please refer to :
  36064. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36065. */
  36066. function UniformBuffer(engine, data, dynamic) {
  36067. this._engine = engine;
  36068. this._noUBO = !engine.supportsUniformBuffers;
  36069. this._dynamic = dynamic;
  36070. this._data = data || [];
  36071. this._uniformLocations = {};
  36072. this._uniformSizes = {};
  36073. this._uniformLocationPointer = 0;
  36074. this._needSync = false;
  36075. if (this._noUBO) {
  36076. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36077. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36078. this.updateFloat = this._updateFloatForEffect;
  36079. this.updateFloat2 = this._updateFloat2ForEffect;
  36080. this.updateFloat3 = this._updateFloat3ForEffect;
  36081. this.updateFloat4 = this._updateFloat4ForEffect;
  36082. this.updateMatrix = this._updateMatrixForEffect;
  36083. this.updateVector3 = this._updateVector3ForEffect;
  36084. this.updateVector4 = this._updateVector4ForEffect;
  36085. this.updateColor3 = this._updateColor3ForEffect;
  36086. this.updateColor4 = this._updateColor4ForEffect;
  36087. }
  36088. else {
  36089. this._engine._uniformBuffers.push(this);
  36090. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36091. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36092. this.updateFloat = this._updateFloatForUniform;
  36093. this.updateFloat2 = this._updateFloat2ForUniform;
  36094. this.updateFloat3 = this._updateFloat3ForUniform;
  36095. this.updateFloat4 = this._updateFloat4ForUniform;
  36096. this.updateMatrix = this._updateMatrixForUniform;
  36097. this.updateVector3 = this._updateVector3ForUniform;
  36098. this.updateVector4 = this._updateVector4ForUniform;
  36099. this.updateColor3 = this._updateColor3ForUniform;
  36100. this.updateColor4 = this._updateColor4ForUniform;
  36101. }
  36102. }
  36103. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36104. // Properties
  36105. /**
  36106. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36107. * or just falling back on setUniformXXX calls.
  36108. */
  36109. get: function () {
  36110. return !this._noUBO;
  36111. },
  36112. enumerable: true,
  36113. configurable: true
  36114. });
  36115. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36116. /**
  36117. * Indicates if the WebGL underlying uniform buffer is in sync
  36118. * with the javascript cache data.
  36119. */
  36120. get: function () {
  36121. return !this._needSync;
  36122. },
  36123. enumerable: true,
  36124. configurable: true
  36125. });
  36126. /**
  36127. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36128. * Also, a dynamic UniformBuffer will disable cache verification and always
  36129. * update the underlying WebGL uniform buffer to the GPU.
  36130. */
  36131. UniformBuffer.prototype.isDynamic = function () {
  36132. return this._dynamic !== undefined;
  36133. };
  36134. /**
  36135. * The data cache on JS side.
  36136. */
  36137. UniformBuffer.prototype.getData = function () {
  36138. return this._bufferData;
  36139. };
  36140. /**
  36141. * The underlying WebGL Uniform buffer.
  36142. */
  36143. UniformBuffer.prototype.getBuffer = function () {
  36144. return this._buffer;
  36145. };
  36146. /**
  36147. * std140 layout specifies how to align data within an UBO structure.
  36148. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36149. * for specs.
  36150. */
  36151. UniformBuffer.prototype._fillAlignment = function (size) {
  36152. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36153. // and 4x4 matrices
  36154. // TODO : change if other types are used
  36155. var alignment;
  36156. if (size <= 2) {
  36157. alignment = size;
  36158. }
  36159. else {
  36160. alignment = 4;
  36161. }
  36162. if ((this._uniformLocationPointer % alignment) !== 0) {
  36163. var oldPointer = this._uniformLocationPointer;
  36164. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36165. var diff = this._uniformLocationPointer - oldPointer;
  36166. for (var i = 0; i < diff; i++) {
  36167. this._data.push(0);
  36168. }
  36169. }
  36170. };
  36171. /**
  36172. * Adds an uniform in the buffer.
  36173. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36174. * for the layout to be correct !
  36175. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36176. * @param {number|number[]} size Data size, or data directly.
  36177. */
  36178. UniformBuffer.prototype.addUniform = function (name, size) {
  36179. if (this._noUBO) {
  36180. return;
  36181. }
  36182. if (this._uniformLocations[name] !== undefined) {
  36183. // Already existing uniform
  36184. return;
  36185. }
  36186. // This function must be called in the order of the shader layout !
  36187. // size can be the size of the uniform, or data directly
  36188. var data;
  36189. if (size instanceof Array) {
  36190. data = size;
  36191. size = data.length;
  36192. }
  36193. else {
  36194. size = size;
  36195. data = [];
  36196. // Fill with zeros
  36197. for (var i = 0; i < size; i++) {
  36198. data.push(0);
  36199. }
  36200. }
  36201. this._fillAlignment(size);
  36202. this._uniformSizes[name] = size;
  36203. this._uniformLocations[name] = this._uniformLocationPointer;
  36204. this._uniformLocationPointer += size;
  36205. for (var i = 0; i < size; i++) {
  36206. this._data.push(data[i]);
  36207. }
  36208. this._needSync = true;
  36209. };
  36210. /**
  36211. * Wrapper for addUniform.
  36212. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36213. * @param {Matrix} mat A 4x4 matrix.
  36214. */
  36215. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36216. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36217. };
  36218. /**
  36219. * Wrapper for addUniform.
  36220. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36221. * @param {number} x
  36222. * @param {number} y
  36223. */
  36224. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36225. var temp = [x, y];
  36226. this.addUniform(name, temp);
  36227. };
  36228. /**
  36229. * Wrapper for addUniform.
  36230. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36231. * @param {number} x
  36232. * @param {number} y
  36233. * @param {number} z
  36234. */
  36235. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36236. var temp = [x, y, z];
  36237. this.addUniform(name, temp);
  36238. };
  36239. /**
  36240. * Wrapper for addUniform.
  36241. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36242. * @param {Color3} color
  36243. */
  36244. UniformBuffer.prototype.addColor3 = function (name, color) {
  36245. var temp = new Array();
  36246. color.toArray(temp);
  36247. this.addUniform(name, temp);
  36248. };
  36249. /**
  36250. * Wrapper for addUniform.
  36251. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36252. * @param {Color3} color
  36253. * @param {number} alpha
  36254. */
  36255. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36256. var temp = new Array();
  36257. color.toArray(temp);
  36258. temp.push(alpha);
  36259. this.addUniform(name, temp);
  36260. };
  36261. /**
  36262. * Wrapper for addUniform.
  36263. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36264. * @param {Vector3} vector
  36265. */
  36266. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36267. var temp = new Array();
  36268. vector.toArray(temp);
  36269. this.addUniform(name, temp);
  36270. };
  36271. /**
  36272. * Wrapper for addUniform.
  36273. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36274. */
  36275. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36276. this.addUniform(name, 12);
  36277. };
  36278. /**
  36279. * Wrapper for addUniform.
  36280. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36281. */
  36282. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36283. this.addUniform(name, 8);
  36284. };
  36285. /**
  36286. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36287. */
  36288. UniformBuffer.prototype.create = function () {
  36289. if (this._noUBO) {
  36290. return;
  36291. }
  36292. if (this._buffer) {
  36293. return; // nothing to do
  36294. }
  36295. // See spec, alignment must be filled as a vec4
  36296. this._fillAlignment(4);
  36297. this._bufferData = new Float32Array(this._data);
  36298. this._rebuild();
  36299. this._needSync = true;
  36300. };
  36301. UniformBuffer.prototype._rebuild = function () {
  36302. if (this._noUBO) {
  36303. return;
  36304. }
  36305. if (this._dynamic) {
  36306. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36307. }
  36308. else {
  36309. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36310. }
  36311. };
  36312. /**
  36313. * Updates the WebGL Uniform Buffer on the GPU.
  36314. * If the `dynamic` flag is set to true, no cache comparison is done.
  36315. * Otherwise, the buffer will be updated only if the cache differs.
  36316. */
  36317. UniformBuffer.prototype.update = function () {
  36318. if (!this._buffer) {
  36319. this.create();
  36320. return;
  36321. }
  36322. if (!this._dynamic && !this._needSync) {
  36323. return;
  36324. }
  36325. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36326. this._needSync = false;
  36327. };
  36328. /**
  36329. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36330. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36331. * @param {number[]|Float32Array} data Flattened data
  36332. * @param {number} size Size of the data.
  36333. */
  36334. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36335. var location = this._uniformLocations[uniformName];
  36336. if (location === undefined) {
  36337. if (this._buffer) {
  36338. // Cannot add an uniform if the buffer is already created
  36339. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36340. return;
  36341. }
  36342. this.addUniform(uniformName, size);
  36343. location = this._uniformLocations[uniformName];
  36344. }
  36345. if (!this._buffer) {
  36346. this.create();
  36347. }
  36348. if (!this._dynamic) {
  36349. // Cache for static uniform buffers
  36350. var changed = false;
  36351. for (var i = 0; i < size; i++) {
  36352. if (this._bufferData[location + i] !== data[i]) {
  36353. changed = true;
  36354. this._bufferData[location + i] = data[i];
  36355. }
  36356. }
  36357. this._needSync = this._needSync || changed;
  36358. }
  36359. else {
  36360. // No cache for dynamic
  36361. for (var i = 0; i < size; i++) {
  36362. this._bufferData[location + i] = data[i];
  36363. }
  36364. }
  36365. };
  36366. // Update methods
  36367. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36368. // To match std140, matrix must be realigned
  36369. for (var i = 0; i < 3; i++) {
  36370. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36371. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36372. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36373. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36374. }
  36375. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36376. };
  36377. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36378. this._currentEffect.setMatrix3x3(name, matrix);
  36379. };
  36380. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36381. this._currentEffect.setMatrix2x2(name, matrix);
  36382. };
  36383. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36384. // To match std140, matrix must be realigned
  36385. for (var i = 0; i < 2; i++) {
  36386. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36387. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36388. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36389. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36390. }
  36391. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36392. };
  36393. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36394. this._currentEffect.setFloat(name, x);
  36395. };
  36396. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36397. UniformBuffer._tempBuffer[0] = x;
  36398. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36399. };
  36400. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36401. if (suffix === void 0) { suffix = ""; }
  36402. this._currentEffect.setFloat2(name + suffix, x, y);
  36403. };
  36404. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36405. if (suffix === void 0) { suffix = ""; }
  36406. UniformBuffer._tempBuffer[0] = x;
  36407. UniformBuffer._tempBuffer[1] = y;
  36408. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36409. };
  36410. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36411. if (suffix === void 0) { suffix = ""; }
  36412. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36413. };
  36414. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36415. if (suffix === void 0) { suffix = ""; }
  36416. UniformBuffer._tempBuffer[0] = x;
  36417. UniformBuffer._tempBuffer[1] = y;
  36418. UniformBuffer._tempBuffer[2] = z;
  36419. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36420. };
  36421. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36422. if (suffix === void 0) { suffix = ""; }
  36423. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36424. };
  36425. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36426. if (suffix === void 0) { suffix = ""; }
  36427. UniformBuffer._tempBuffer[0] = x;
  36428. UniformBuffer._tempBuffer[1] = y;
  36429. UniformBuffer._tempBuffer[2] = z;
  36430. UniformBuffer._tempBuffer[3] = w;
  36431. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36432. };
  36433. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36434. this._currentEffect.setMatrix(name, mat);
  36435. };
  36436. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36437. this.updateUniform(name, mat.toArray(), 16);
  36438. };
  36439. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36440. this._currentEffect.setVector3(name, vector);
  36441. };
  36442. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36443. vector.toArray(UniformBuffer._tempBuffer);
  36444. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36445. };
  36446. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36447. this._currentEffect.setVector4(name, vector);
  36448. };
  36449. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36450. vector.toArray(UniformBuffer._tempBuffer);
  36451. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36452. };
  36453. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36454. if (suffix === void 0) { suffix = ""; }
  36455. this._currentEffect.setColor3(name + suffix, color);
  36456. };
  36457. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36458. if (suffix === void 0) { suffix = ""; }
  36459. color.toArray(UniformBuffer._tempBuffer);
  36460. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36461. };
  36462. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36463. if (suffix === void 0) { suffix = ""; }
  36464. this._currentEffect.setColor4(name + suffix, color, alpha);
  36465. };
  36466. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36467. if (suffix === void 0) { suffix = ""; }
  36468. color.toArray(UniformBuffer._tempBuffer);
  36469. UniformBuffer._tempBuffer[3] = alpha;
  36470. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36471. };
  36472. /**
  36473. * Sets a sampler uniform on the effect.
  36474. * @param {string} name Name of the sampler.
  36475. * @param {Texture} texture
  36476. */
  36477. UniformBuffer.prototype.setTexture = function (name, texture) {
  36478. this._currentEffect.setTexture(name, texture);
  36479. };
  36480. /**
  36481. * Directly updates the value of the uniform in the cache AND on the GPU.
  36482. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36483. * @param {number[]|Float32Array} data Flattened data
  36484. */
  36485. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36486. this.updateUniform(uniformName, data, data.length);
  36487. this.update();
  36488. };
  36489. /**
  36490. * Binds this uniform buffer to an effect.
  36491. * @param {Effect} effect
  36492. * @param {string} name Name of the uniform block in the shader.
  36493. */
  36494. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36495. this._currentEffect = effect;
  36496. if (this._noUBO || !this._buffer) {
  36497. return;
  36498. }
  36499. effect.bindUniformBuffer(this._buffer, name);
  36500. };
  36501. /**
  36502. * Disposes the uniform buffer.
  36503. */
  36504. UniformBuffer.prototype.dispose = function () {
  36505. if (this._noUBO) {
  36506. return;
  36507. }
  36508. var index = this._engine._uniformBuffers.indexOf(this);
  36509. if (index !== -1) {
  36510. this._engine._uniformBuffers.splice(index, 1);
  36511. }
  36512. if (!this._buffer) {
  36513. return;
  36514. }
  36515. if (this._engine._releaseBuffer(this._buffer)) {
  36516. this._buffer = null;
  36517. }
  36518. };
  36519. // Pool for avoiding memory leaks
  36520. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36521. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36522. return UniformBuffer;
  36523. }());
  36524. BABYLON.UniformBuffer = UniformBuffer;
  36525. })(BABYLON || (BABYLON = {}));
  36526. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36527. var BABYLON;
  36528. (function (BABYLON) {
  36529. /**
  36530. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36531. */
  36532. var VertexData = /** @class */ (function () {
  36533. function VertexData() {
  36534. }
  36535. /**
  36536. * Uses the passed data array to set the set the values for the specified kind of data
  36537. * @param data a linear array of floating numbers
  36538. * @param kind the type of data that is being set, eg positions, colors etc
  36539. */
  36540. VertexData.prototype.set = function (data, kind) {
  36541. switch (kind) {
  36542. case BABYLON.VertexBuffer.PositionKind:
  36543. this.positions = data;
  36544. break;
  36545. case BABYLON.VertexBuffer.NormalKind:
  36546. this.normals = data;
  36547. break;
  36548. case BABYLON.VertexBuffer.TangentKind:
  36549. this.tangents = data;
  36550. break;
  36551. case BABYLON.VertexBuffer.UVKind:
  36552. this.uvs = data;
  36553. break;
  36554. case BABYLON.VertexBuffer.UV2Kind:
  36555. this.uvs2 = data;
  36556. break;
  36557. case BABYLON.VertexBuffer.UV3Kind:
  36558. this.uvs3 = data;
  36559. break;
  36560. case BABYLON.VertexBuffer.UV4Kind:
  36561. this.uvs4 = data;
  36562. break;
  36563. case BABYLON.VertexBuffer.UV5Kind:
  36564. this.uvs5 = data;
  36565. break;
  36566. case BABYLON.VertexBuffer.UV6Kind:
  36567. this.uvs6 = data;
  36568. break;
  36569. case BABYLON.VertexBuffer.ColorKind:
  36570. this.colors = data;
  36571. break;
  36572. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36573. this.matricesIndices = data;
  36574. break;
  36575. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36576. this.matricesWeights = data;
  36577. break;
  36578. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36579. this.matricesIndicesExtra = data;
  36580. break;
  36581. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36582. this.matricesWeightsExtra = data;
  36583. break;
  36584. }
  36585. };
  36586. /**
  36587. * Associates the vertexData to the passed Mesh.
  36588. * Sets it as updatable or not (default `false`)
  36589. * @param mesh the mesh the vertexData is applied to
  36590. * @param updatable when used and having the value true allows new data to update the vertexData
  36591. * @returns the VertexData
  36592. */
  36593. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36594. this._applyTo(mesh, updatable);
  36595. return this;
  36596. };
  36597. /**
  36598. * Associates the vertexData to the passed Geometry.
  36599. * Sets it as updatable or not (default `false`)
  36600. * @param geometry the geometry the vertexData is applied to
  36601. * @param updatable when used and having the value true allows new data to update the vertexData
  36602. * @returns VertexData
  36603. */
  36604. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36605. this._applyTo(geometry, updatable);
  36606. return this;
  36607. };
  36608. /**
  36609. * Updates the associated mesh
  36610. * @param mesh the mesh to be updated
  36611. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36612. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36613. * @returns VertexData
  36614. */
  36615. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36616. this._update(mesh);
  36617. return this;
  36618. };
  36619. /**
  36620. * Updates the associated geometry
  36621. * @param geometry the geometry to be updated
  36622. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36623. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36624. * @returns VertexData.
  36625. */
  36626. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36627. this._update(geometry);
  36628. return this;
  36629. };
  36630. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36631. if (updatable === void 0) { updatable = false; }
  36632. if (this.positions) {
  36633. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36634. }
  36635. if (this.normals) {
  36636. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36637. }
  36638. if (this.tangents) {
  36639. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36640. }
  36641. if (this.uvs) {
  36642. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36643. }
  36644. if (this.uvs2) {
  36645. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36646. }
  36647. if (this.uvs3) {
  36648. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36649. }
  36650. if (this.uvs4) {
  36651. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36652. }
  36653. if (this.uvs5) {
  36654. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36655. }
  36656. if (this.uvs6) {
  36657. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36658. }
  36659. if (this.colors) {
  36660. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36661. }
  36662. if (this.matricesIndices) {
  36663. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36664. }
  36665. if (this.matricesWeights) {
  36666. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36667. }
  36668. if (this.matricesIndicesExtra) {
  36669. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36670. }
  36671. if (this.matricesWeightsExtra) {
  36672. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36673. }
  36674. if (this.indices) {
  36675. meshOrGeometry.setIndices(this.indices, null, updatable);
  36676. }
  36677. else {
  36678. meshOrGeometry.setIndices([], null);
  36679. }
  36680. return this;
  36681. };
  36682. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36683. if (this.positions) {
  36684. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36685. }
  36686. if (this.normals) {
  36687. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36688. }
  36689. if (this.tangents) {
  36690. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36691. }
  36692. if (this.uvs) {
  36693. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36694. }
  36695. if (this.uvs2) {
  36696. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36697. }
  36698. if (this.uvs3) {
  36699. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36700. }
  36701. if (this.uvs4) {
  36702. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36703. }
  36704. if (this.uvs5) {
  36705. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36706. }
  36707. if (this.uvs6) {
  36708. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36709. }
  36710. if (this.colors) {
  36711. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36712. }
  36713. if (this.matricesIndices) {
  36714. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36715. }
  36716. if (this.matricesWeights) {
  36717. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36718. }
  36719. if (this.matricesIndicesExtra) {
  36720. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36721. }
  36722. if (this.matricesWeightsExtra) {
  36723. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36724. }
  36725. if (this.indices) {
  36726. meshOrGeometry.setIndices(this.indices, null);
  36727. }
  36728. return this;
  36729. };
  36730. /**
  36731. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36732. * @param matrix the transforming matrix
  36733. * @returns the VertexData
  36734. */
  36735. VertexData.prototype.transform = function (matrix) {
  36736. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36737. var transformed = BABYLON.Vector3.Zero();
  36738. var index;
  36739. if (this.positions) {
  36740. var position = BABYLON.Vector3.Zero();
  36741. for (index = 0; index < this.positions.length; index += 3) {
  36742. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36743. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36744. this.positions[index] = transformed.x;
  36745. this.positions[index + 1] = transformed.y;
  36746. this.positions[index + 2] = transformed.z;
  36747. }
  36748. }
  36749. if (this.normals) {
  36750. var normal = BABYLON.Vector3.Zero();
  36751. for (index = 0; index < this.normals.length; index += 3) {
  36752. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36753. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36754. this.normals[index] = transformed.x;
  36755. this.normals[index + 1] = transformed.y;
  36756. this.normals[index + 2] = transformed.z;
  36757. }
  36758. }
  36759. if (this.tangents) {
  36760. var tangent = BABYLON.Vector4.Zero();
  36761. var tangentTransformed = BABYLON.Vector4.Zero();
  36762. for (index = 0; index < this.tangents.length; index += 4) {
  36763. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36764. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36765. this.tangents[index] = tangentTransformed.x;
  36766. this.tangents[index + 1] = tangentTransformed.y;
  36767. this.tangents[index + 2] = tangentTransformed.z;
  36768. this.tangents[index + 3] = tangentTransformed.w;
  36769. }
  36770. }
  36771. if (flip && this.indices) {
  36772. for (index = 0; index < this.indices.length; index += 3) {
  36773. var tmp = this.indices[index + 1];
  36774. this.indices[index + 1] = this.indices[index + 2];
  36775. this.indices[index + 2] = tmp;
  36776. }
  36777. }
  36778. return this;
  36779. };
  36780. /**
  36781. * Merges the passed VertexData into the current one
  36782. * @param other the VertexData to be merged into the current one
  36783. * @returns the modified VertexData
  36784. */
  36785. VertexData.prototype.merge = function (other) {
  36786. this._validate();
  36787. other._validate();
  36788. if (!this.normals !== !other.normals ||
  36789. !this.tangents !== !other.tangents ||
  36790. !this.uvs !== !other.uvs ||
  36791. !this.uvs2 !== !other.uvs2 ||
  36792. !this.uvs3 !== !other.uvs3 ||
  36793. !this.uvs4 !== !other.uvs4 ||
  36794. !this.uvs5 !== !other.uvs5 ||
  36795. !this.uvs6 !== !other.uvs6 ||
  36796. !this.colors !== !other.colors ||
  36797. !this.matricesIndices !== !other.matricesIndices ||
  36798. !this.matricesWeights !== !other.matricesWeights ||
  36799. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36800. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36801. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36802. }
  36803. if (other.indices) {
  36804. if (!this.indices) {
  36805. this.indices = [];
  36806. }
  36807. var offset = this.positions ? this.positions.length / 3 : 0;
  36808. for (var index = 0; index < other.indices.length; index++) {
  36809. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36810. this.indices.push(other.indices[index] + offset);
  36811. }
  36812. }
  36813. this.positions = this._mergeElement(this.positions, other.positions);
  36814. this.normals = this._mergeElement(this.normals, other.normals);
  36815. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36816. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36817. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36818. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36819. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36820. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36821. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36822. this.colors = this._mergeElement(this.colors, other.colors);
  36823. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36824. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36825. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36826. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36827. return this;
  36828. };
  36829. VertexData.prototype._mergeElement = function (source, other) {
  36830. if (!source) {
  36831. return other;
  36832. }
  36833. if (!other) {
  36834. return source;
  36835. }
  36836. var len = other.length + source.length;
  36837. var isSrcTypedArray = source instanceof Float32Array;
  36838. var isOthTypedArray = other instanceof Float32Array;
  36839. // use non-loop method when the source is Float32Array
  36840. if (isSrcTypedArray) {
  36841. var ret32 = new Float32Array(len);
  36842. ret32.set(source);
  36843. ret32.set(other, source.length);
  36844. return ret32;
  36845. // source is number[], when other is also use concat
  36846. }
  36847. else if (!isOthTypedArray) {
  36848. return source.concat(other);
  36849. // source is a number[], but other is a Float32Array, loop required
  36850. }
  36851. else {
  36852. var ret = source.slice(0); // copy source to a separate array
  36853. for (var i = 0, len = other.length; i < len; i++) {
  36854. ret.push(other[i]);
  36855. }
  36856. return ret;
  36857. }
  36858. };
  36859. VertexData.prototype._validate = function () {
  36860. if (!this.positions) {
  36861. throw new Error("Positions are required");
  36862. }
  36863. var getElementCount = function (kind, values) {
  36864. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36865. if ((values.length % stride) !== 0) {
  36866. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36867. }
  36868. return values.length / stride;
  36869. };
  36870. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36871. var validateElementCount = function (kind, values) {
  36872. var elementCount = getElementCount(kind, values);
  36873. if (elementCount !== positionsElementCount) {
  36874. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36875. }
  36876. };
  36877. if (this.normals)
  36878. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36879. if (this.tangents)
  36880. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36881. if (this.uvs)
  36882. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36883. if (this.uvs2)
  36884. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36885. if (this.uvs3)
  36886. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36887. if (this.uvs4)
  36888. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36889. if (this.uvs5)
  36890. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36891. if (this.uvs6)
  36892. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36893. if (this.colors)
  36894. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36895. if (this.matricesIndices)
  36896. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36897. if (this.matricesWeights)
  36898. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36899. if (this.matricesIndicesExtra)
  36900. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36901. if (this.matricesWeightsExtra)
  36902. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36903. };
  36904. /**
  36905. * Serializes the VertexData
  36906. * @returns a serialized object
  36907. */
  36908. VertexData.prototype.serialize = function () {
  36909. var serializationObject = this.serialize();
  36910. if (this.positions) {
  36911. serializationObject.positions = this.positions;
  36912. }
  36913. if (this.normals) {
  36914. serializationObject.normals = this.normals;
  36915. }
  36916. if (this.tangents) {
  36917. serializationObject.tangents = this.tangents;
  36918. }
  36919. if (this.uvs) {
  36920. serializationObject.uvs = this.uvs;
  36921. }
  36922. if (this.uvs2) {
  36923. serializationObject.uvs2 = this.uvs2;
  36924. }
  36925. if (this.uvs3) {
  36926. serializationObject.uvs3 = this.uvs3;
  36927. }
  36928. if (this.uvs4) {
  36929. serializationObject.uvs4 = this.uvs4;
  36930. }
  36931. if (this.uvs5) {
  36932. serializationObject.uvs5 = this.uvs5;
  36933. }
  36934. if (this.uvs6) {
  36935. serializationObject.uvs6 = this.uvs6;
  36936. }
  36937. if (this.colors) {
  36938. serializationObject.colors = this.colors;
  36939. }
  36940. if (this.matricesIndices) {
  36941. serializationObject.matricesIndices = this.matricesIndices;
  36942. serializationObject.matricesIndices._isExpanded = true;
  36943. }
  36944. if (this.matricesWeights) {
  36945. serializationObject.matricesWeights = this.matricesWeights;
  36946. }
  36947. if (this.matricesIndicesExtra) {
  36948. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36949. serializationObject.matricesIndicesExtra._isExpanded = true;
  36950. }
  36951. if (this.matricesWeightsExtra) {
  36952. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36953. }
  36954. serializationObject.indices = this.indices;
  36955. return serializationObject;
  36956. };
  36957. // Statics
  36958. /**
  36959. * Extracts the vertexData from a mesh
  36960. * @param mesh the mesh from which to extract the VertexData
  36961. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36962. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36963. * @returns the object VertexData associated to the passed mesh
  36964. */
  36965. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36966. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36967. };
  36968. /**
  36969. * Extracts the vertexData from the geometry
  36970. * @param geometry the geometry from which to extract the VertexData
  36971. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36972. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36973. * @returns the object VertexData associated to the passed mesh
  36974. */
  36975. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36976. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36977. };
  36978. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36979. var result = new VertexData();
  36980. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36981. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36982. }
  36983. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36984. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36985. }
  36986. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36987. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36988. }
  36989. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36990. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36991. }
  36992. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36993. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36994. }
  36995. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36996. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36997. }
  36998. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36999. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37000. }
  37001. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37002. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37003. }
  37004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37005. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37006. }
  37007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37008. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37009. }
  37010. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37011. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37012. }
  37013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37014. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37015. }
  37016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37017. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37018. }
  37019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37020. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37021. }
  37022. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37023. return result;
  37024. };
  37025. /**
  37026. * Creates the VertexData for a Ribbon
  37027. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37028. * * pathArray array of paths, each of which an array of successive Vector3
  37029. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37030. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37031. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  37032. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37033. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37034. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37035. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37036. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37037. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37038. * @returns the VertexData of the ribbon
  37039. */
  37040. VertexData.CreateRibbon = function (options) {
  37041. var pathArray = options.pathArray;
  37042. var closeArray = options.closeArray || false;
  37043. var closePath = options.closePath || false;
  37044. var invertUV = options.invertUV || false;
  37045. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37046. var offset = options.offset || defaultOffset;
  37047. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37048. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37049. var customUV = options.uvs;
  37050. var customColors = options.colors;
  37051. var positions = [];
  37052. var indices = [];
  37053. var normals = [];
  37054. var uvs = [];
  37055. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37056. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37057. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37058. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37059. var minlg; // minimal length among all paths from pathArray
  37060. var lg = []; // array of path lengths : nb of vertex per path
  37061. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37062. var p; // path iterator
  37063. var i; // point iterator
  37064. var j; // point iterator
  37065. // if single path in pathArray
  37066. if (pathArray.length < 2) {
  37067. var ar1 = [];
  37068. var ar2 = [];
  37069. for (i = 0; i < pathArray[0].length - offset; i++) {
  37070. ar1.push(pathArray[0][i]);
  37071. ar2.push(pathArray[0][i + offset]);
  37072. }
  37073. pathArray = [ar1, ar2];
  37074. }
  37075. // positions and horizontal distances (u)
  37076. var idc = 0;
  37077. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37078. var path;
  37079. var l;
  37080. minlg = pathArray[0].length;
  37081. var vectlg;
  37082. var dist;
  37083. for (p = 0; p < pathArray.length; p++) {
  37084. uTotalDistance[p] = 0;
  37085. us[p] = [0];
  37086. path = pathArray[p];
  37087. l = path.length;
  37088. minlg = (minlg < l) ? minlg : l;
  37089. j = 0;
  37090. while (j < l) {
  37091. positions.push(path[j].x, path[j].y, path[j].z);
  37092. if (j > 0) {
  37093. vectlg = path[j].subtract(path[j - 1]).length();
  37094. dist = vectlg + uTotalDistance[p];
  37095. us[p].push(dist);
  37096. uTotalDistance[p] = dist;
  37097. }
  37098. j++;
  37099. }
  37100. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37101. j--;
  37102. positions.push(path[0].x, path[0].y, path[0].z);
  37103. vectlg = path[j].subtract(path[0]).length();
  37104. dist = vectlg + uTotalDistance[p];
  37105. us[p].push(dist);
  37106. uTotalDistance[p] = dist;
  37107. }
  37108. lg[p] = l + closePathCorr;
  37109. idx[p] = idc;
  37110. idc += (l + closePathCorr);
  37111. }
  37112. // vertical distances (v)
  37113. var path1;
  37114. var path2;
  37115. var vertex1 = null;
  37116. var vertex2 = null;
  37117. for (i = 0; i < minlg + closePathCorr; i++) {
  37118. vTotalDistance[i] = 0;
  37119. vs[i] = [0];
  37120. for (p = 0; p < pathArray.length - 1; p++) {
  37121. path1 = pathArray[p];
  37122. path2 = pathArray[p + 1];
  37123. if (i === minlg) { // closePath
  37124. vertex1 = path1[0];
  37125. vertex2 = path2[0];
  37126. }
  37127. else {
  37128. vertex1 = path1[i];
  37129. vertex2 = path2[i];
  37130. }
  37131. vectlg = vertex2.subtract(vertex1).length();
  37132. dist = vectlg + vTotalDistance[i];
  37133. vs[i].push(dist);
  37134. vTotalDistance[i] = dist;
  37135. }
  37136. if (closeArray && vertex2 && vertex1) {
  37137. path1 = pathArray[p];
  37138. path2 = pathArray[0];
  37139. if (i === minlg) { // closePath
  37140. vertex2 = path2[0];
  37141. }
  37142. vectlg = vertex2.subtract(vertex1).length();
  37143. dist = vectlg + vTotalDistance[i];
  37144. vTotalDistance[i] = dist;
  37145. }
  37146. }
  37147. // uvs
  37148. var u;
  37149. var v;
  37150. if (customUV) {
  37151. for (p = 0; p < customUV.length; p++) {
  37152. uvs.push(customUV[p].x, customUV[p].y);
  37153. }
  37154. }
  37155. else {
  37156. for (p = 0; p < pathArray.length; p++) {
  37157. for (i = 0; i < minlg + closePathCorr; i++) {
  37158. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37159. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37160. if (invertUV) {
  37161. uvs.push(v, u);
  37162. }
  37163. else {
  37164. uvs.push(u, v);
  37165. }
  37166. }
  37167. }
  37168. }
  37169. // indices
  37170. p = 0; // path index
  37171. var pi = 0; // positions array index
  37172. var l1 = lg[p] - 1; // path1 length
  37173. var l2 = lg[p + 1] - 1; // path2 length
  37174. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37175. var shft = idx[1] - idx[0]; // shift
  37176. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37177. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37178. // 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
  37179. indices.push(pi, pi + shft, pi + 1);
  37180. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37181. pi += 1;
  37182. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37183. p++;
  37184. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37185. shft = idx[0] - idx[p];
  37186. l1 = lg[p] - 1;
  37187. l2 = lg[0] - 1;
  37188. }
  37189. else {
  37190. shft = idx[p + 1] - idx[p];
  37191. l1 = lg[p] - 1;
  37192. l2 = lg[p + 1] - 1;
  37193. }
  37194. pi = idx[p];
  37195. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37196. }
  37197. }
  37198. // normals
  37199. VertexData.ComputeNormals(positions, indices, normals);
  37200. if (closePath) { // update both the first and last vertex normals to their average value
  37201. var indexFirst = 0;
  37202. var indexLast = 0;
  37203. for (p = 0; p < pathArray.length; p++) {
  37204. indexFirst = idx[p] * 3;
  37205. if (p + 1 < pathArray.length) {
  37206. indexLast = (idx[p + 1] - 1) * 3;
  37207. }
  37208. else {
  37209. indexLast = normals.length - 3;
  37210. }
  37211. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37212. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37213. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37214. normals[indexLast] = normals[indexFirst];
  37215. normals[indexLast + 1] = normals[indexFirst + 1];
  37216. normals[indexLast + 2] = normals[indexFirst + 2];
  37217. }
  37218. }
  37219. // sides
  37220. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37221. // Colors
  37222. var colors = null;
  37223. if (customColors) {
  37224. colors = new Float32Array(customColors.length * 4);
  37225. for (var c = 0; c < customColors.length; c++) {
  37226. colors[c * 4] = customColors[c].r;
  37227. colors[c * 4 + 1] = customColors[c].g;
  37228. colors[c * 4 + 2] = customColors[c].b;
  37229. colors[c * 4 + 3] = customColors[c].a;
  37230. }
  37231. }
  37232. // Result
  37233. var vertexData = new VertexData();
  37234. var positions32 = new Float32Array(positions);
  37235. var normals32 = new Float32Array(normals);
  37236. var uvs32 = new Float32Array(uvs);
  37237. vertexData.indices = indices;
  37238. vertexData.positions = positions32;
  37239. vertexData.normals = normals32;
  37240. vertexData.uvs = uvs32;
  37241. if (colors) {
  37242. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37243. }
  37244. if (closePath) {
  37245. vertexData._idx = idx;
  37246. }
  37247. return vertexData;
  37248. };
  37249. /**
  37250. * Creates the VertexData for a box
  37251. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37252. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37253. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37254. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37255. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37256. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37257. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37258. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37259. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37260. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37261. * @returns the VertexData of the box
  37262. */
  37263. VertexData.CreateBox = function (options) {
  37264. var normalsSource = [
  37265. new BABYLON.Vector3(0, 0, 1),
  37266. new BABYLON.Vector3(0, 0, -1),
  37267. new BABYLON.Vector3(1, 0, 0),
  37268. new BABYLON.Vector3(-1, 0, 0),
  37269. new BABYLON.Vector3(0, 1, 0),
  37270. new BABYLON.Vector3(0, -1, 0)
  37271. ];
  37272. var indices = [];
  37273. var positions = [];
  37274. var normals = [];
  37275. var uvs = [];
  37276. var width = options.width || options.size || 1;
  37277. var height = options.height || options.size || 1;
  37278. var depth = options.depth || options.size || 1;
  37279. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37280. var faceUV = options.faceUV || new Array(6);
  37281. var faceColors = options.faceColors;
  37282. var colors = [];
  37283. // default face colors and UV if undefined
  37284. for (var f = 0; f < 6; f++) {
  37285. if (faceUV[f] === undefined) {
  37286. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37287. }
  37288. if (faceColors && faceColors[f] === undefined) {
  37289. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37290. }
  37291. }
  37292. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37293. // Create each face in turn.
  37294. for (var index = 0; index < normalsSource.length; index++) {
  37295. var normal = normalsSource[index];
  37296. // Get two vectors perpendicular to the face normal and to each other.
  37297. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37298. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37299. // Six indices (two triangles) per face.
  37300. var verticesLength = positions.length / 3;
  37301. indices.push(verticesLength);
  37302. indices.push(verticesLength + 1);
  37303. indices.push(verticesLength + 2);
  37304. indices.push(verticesLength);
  37305. indices.push(verticesLength + 2);
  37306. indices.push(verticesLength + 3);
  37307. // Four vertices per face.
  37308. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37309. positions.push(vertex.x, vertex.y, vertex.z);
  37310. normals.push(normal.x, normal.y, normal.z);
  37311. uvs.push(faceUV[index].z, faceUV[index].w);
  37312. if (faceColors) {
  37313. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37314. }
  37315. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37316. positions.push(vertex.x, vertex.y, vertex.z);
  37317. normals.push(normal.x, normal.y, normal.z);
  37318. uvs.push(faceUV[index].x, faceUV[index].w);
  37319. if (faceColors) {
  37320. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37321. }
  37322. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37323. positions.push(vertex.x, vertex.y, vertex.z);
  37324. normals.push(normal.x, normal.y, normal.z);
  37325. uvs.push(faceUV[index].x, faceUV[index].y);
  37326. if (faceColors) {
  37327. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37328. }
  37329. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37330. positions.push(vertex.x, vertex.y, vertex.z);
  37331. normals.push(normal.x, normal.y, normal.z);
  37332. uvs.push(faceUV[index].z, faceUV[index].y);
  37333. if (faceColors) {
  37334. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37335. }
  37336. }
  37337. // sides
  37338. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37339. // Result
  37340. var vertexData = new VertexData();
  37341. vertexData.indices = indices;
  37342. vertexData.positions = positions;
  37343. vertexData.normals = normals;
  37344. vertexData.uvs = uvs;
  37345. if (faceColors) {
  37346. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37347. vertexData.colors = totalColors;
  37348. }
  37349. return vertexData;
  37350. };
  37351. /**
  37352. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37353. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37354. * * segments sets the number of horizontal strips optional, default 32
  37355. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37356. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37357. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37358. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37359. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  37360. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  37361. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37362. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37363. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37364. * @returns the VertexData of the ellipsoid
  37365. */
  37366. VertexData.CreateSphere = function (options) {
  37367. var segments = options.segments || 32;
  37368. var diameterX = options.diameterX || options.diameter || 1;
  37369. var diameterY = options.diameterY || options.diameter || 1;
  37370. var diameterZ = options.diameterZ || options.diameter || 1;
  37371. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37372. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37373. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37374. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37375. var totalZRotationSteps = 2 + segments;
  37376. var totalYRotationSteps = 2 * totalZRotationSteps;
  37377. var indices = [];
  37378. var positions = [];
  37379. var normals = [];
  37380. var uvs = [];
  37381. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37382. var normalizedZ = zRotationStep / totalZRotationSteps;
  37383. var angleZ = normalizedZ * Math.PI * slice;
  37384. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37385. var normalizedY = yRotationStep / totalYRotationSteps;
  37386. var angleY = normalizedY * Math.PI * 2 * arc;
  37387. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37388. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37389. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37390. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37391. var vertex = complete.multiply(radius);
  37392. var normal = complete.divide(radius).normalize();
  37393. positions.push(vertex.x, vertex.y, vertex.z);
  37394. normals.push(normal.x, normal.y, normal.z);
  37395. uvs.push(normalizedY, normalizedZ);
  37396. }
  37397. if (zRotationStep > 0) {
  37398. var verticesCount = positions.length / 3;
  37399. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37400. indices.push((firstIndex));
  37401. indices.push((firstIndex + 1));
  37402. indices.push(firstIndex + totalYRotationSteps + 1);
  37403. indices.push((firstIndex + totalYRotationSteps + 1));
  37404. indices.push((firstIndex + 1));
  37405. indices.push((firstIndex + totalYRotationSteps + 2));
  37406. }
  37407. }
  37408. }
  37409. // Sides
  37410. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37411. // Result
  37412. var vertexData = new VertexData();
  37413. vertexData.indices = indices;
  37414. vertexData.positions = positions;
  37415. vertexData.normals = normals;
  37416. vertexData.uvs = uvs;
  37417. return vertexData;
  37418. };
  37419. /**
  37420. * Creates the VertexData for a cylinder, cone or prism
  37421. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37422. * * height sets the height (y direction) of the cylinder, optional, default 2
  37423. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37424. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37425. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37426. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37427. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37428. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37429. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37430. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37431. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37432. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37433. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37434. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37435. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37436. * @returns the VertexData of the cylinder, cone or prism
  37437. */
  37438. VertexData.CreateCylinder = function (options) {
  37439. var height = options.height || 2;
  37440. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37441. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37442. var tessellation = options.tessellation || 24;
  37443. var subdivisions = options.subdivisions || 1;
  37444. var hasRings = options.hasRings ? true : false;
  37445. var enclose = options.enclose ? true : false;
  37446. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37447. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37448. var faceUV = options.faceUV || new Array(3);
  37449. var faceColors = options.faceColors;
  37450. // default face colors and UV if undefined
  37451. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37452. var ringNb = (hasRings) ? subdivisions : 1;
  37453. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37454. var f;
  37455. for (f = 0; f < surfaceNb; f++) {
  37456. if (faceColors && faceColors[f] === undefined) {
  37457. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37458. }
  37459. }
  37460. for (f = 0; f < surfaceNb; f++) {
  37461. if (faceUV && faceUV[f] === undefined) {
  37462. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37463. }
  37464. }
  37465. var indices = new Array();
  37466. var positions = new Array();
  37467. var normals = new Array();
  37468. var uvs = new Array();
  37469. var colors = new Array();
  37470. var angle_step = Math.PI * 2 * arc / tessellation;
  37471. var angle;
  37472. var h;
  37473. var radius;
  37474. var tan = (diameterBottom - diameterTop) / 2 / height;
  37475. var ringVertex = BABYLON.Vector3.Zero();
  37476. var ringNormal = BABYLON.Vector3.Zero();
  37477. var ringFirstVertex = BABYLON.Vector3.Zero();
  37478. var ringFirstNormal = BABYLON.Vector3.Zero();
  37479. var quadNormal = BABYLON.Vector3.Zero();
  37480. var Y = BABYLON.Axis.Y;
  37481. // positions, normals, uvs
  37482. var i;
  37483. var j;
  37484. var r;
  37485. var ringIdx = 1;
  37486. var s = 1; // surface index
  37487. var cs = 0;
  37488. var v = 0;
  37489. for (i = 0; i <= subdivisions; i++) {
  37490. h = i / subdivisions;
  37491. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37492. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37493. for (r = 0; r < ringIdx; r++) {
  37494. if (hasRings) {
  37495. s += r;
  37496. }
  37497. if (enclose) {
  37498. s += 2 * r;
  37499. }
  37500. for (j = 0; j <= tessellation; j++) {
  37501. angle = j * angle_step;
  37502. // position
  37503. ringVertex.x = Math.cos(-angle) * radius;
  37504. ringVertex.y = -height / 2 + h * height;
  37505. ringVertex.z = Math.sin(-angle) * radius;
  37506. // normal
  37507. if (diameterTop === 0 && i === subdivisions) {
  37508. // if no top cap, reuse former normals
  37509. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37510. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37511. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37512. }
  37513. else {
  37514. ringNormal.x = ringVertex.x;
  37515. ringNormal.z = ringVertex.z;
  37516. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37517. ringNormal.normalize();
  37518. }
  37519. // keep first ring vertex values for enclose
  37520. if (j === 0) {
  37521. ringFirstVertex.copyFrom(ringVertex);
  37522. ringFirstNormal.copyFrom(ringNormal);
  37523. }
  37524. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37525. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37526. if (hasRings) {
  37527. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37528. }
  37529. else {
  37530. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37531. }
  37532. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37533. if (faceColors) {
  37534. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37535. }
  37536. }
  37537. // if enclose, add four vertices and their dedicated normals
  37538. if (arc !== 1 && enclose) {
  37539. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37540. positions.push(0, ringVertex.y, 0);
  37541. positions.push(0, ringVertex.y, 0);
  37542. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37543. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37544. quadNormal.normalize();
  37545. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37546. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37547. quadNormal.normalize();
  37548. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37549. if (hasRings) {
  37550. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37551. }
  37552. else {
  37553. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37554. }
  37555. uvs.push(faceUV[s + 1].x, v);
  37556. uvs.push(faceUV[s + 1].z, v);
  37557. if (hasRings) {
  37558. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37559. }
  37560. else {
  37561. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37562. }
  37563. uvs.push(faceUV[s + 2].x, v);
  37564. uvs.push(faceUV[s + 2].z, v);
  37565. if (faceColors) {
  37566. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37567. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37568. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37569. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37570. }
  37571. }
  37572. if (cs !== s) {
  37573. cs = s;
  37574. }
  37575. }
  37576. }
  37577. // indices
  37578. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37579. var s;
  37580. i = 0;
  37581. for (s = 0; s < subdivisions; s++) {
  37582. var i0 = 0;
  37583. var i1 = 0;
  37584. var i2 = 0;
  37585. var i3 = 0;
  37586. for (j = 0; j < tessellation; j++) {
  37587. i0 = i * (e + 1) + j;
  37588. i1 = (i + 1) * (e + 1) + j;
  37589. i2 = i * (e + 1) + (j + 1);
  37590. i3 = (i + 1) * (e + 1) + (j + 1);
  37591. indices.push(i0, i1, i2);
  37592. indices.push(i3, i2, i1);
  37593. }
  37594. if (arc !== 1 && enclose) { // if enclose, add two quads
  37595. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37596. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37597. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37598. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37599. }
  37600. i = (hasRings) ? (i + 2) : (i + 1);
  37601. }
  37602. // Caps
  37603. var createCylinderCap = function (isTop) {
  37604. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37605. if (radius === 0) {
  37606. return;
  37607. }
  37608. // Cap positions, normals & uvs
  37609. var angle;
  37610. var circleVector;
  37611. var i;
  37612. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37613. var c = null;
  37614. if (faceColors) {
  37615. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37616. }
  37617. // cap center
  37618. var vbase = positions.length / 3;
  37619. var offset = isTop ? height / 2 : -height / 2;
  37620. var center = new BABYLON.Vector3(0, offset, 0);
  37621. positions.push(center.x, center.y, center.z);
  37622. normals.push(0, isTop ? 1 : -1, 0);
  37623. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37624. if (c) {
  37625. colors.push(c.r, c.g, c.b, c.a);
  37626. }
  37627. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37628. for (i = 0; i <= tessellation; i++) {
  37629. angle = Math.PI * 2 * i * arc / tessellation;
  37630. var cos = Math.cos(-angle);
  37631. var sin = Math.sin(-angle);
  37632. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37633. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37634. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37635. normals.push(0, isTop ? 1 : -1, 0);
  37636. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37637. if (c) {
  37638. colors.push(c.r, c.g, c.b, c.a);
  37639. }
  37640. }
  37641. // Cap indices
  37642. for (i = 0; i < tessellation; i++) {
  37643. if (!isTop) {
  37644. indices.push(vbase);
  37645. indices.push(vbase + (i + 1));
  37646. indices.push(vbase + (i + 2));
  37647. }
  37648. else {
  37649. indices.push(vbase);
  37650. indices.push(vbase + (i + 2));
  37651. indices.push(vbase + (i + 1));
  37652. }
  37653. }
  37654. };
  37655. // add caps to geometry
  37656. createCylinderCap(false);
  37657. createCylinderCap(true);
  37658. // Sides
  37659. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37660. var vertexData = new VertexData();
  37661. vertexData.indices = indices;
  37662. vertexData.positions = positions;
  37663. vertexData.normals = normals;
  37664. vertexData.uvs = uvs;
  37665. if (faceColors) {
  37666. vertexData.colors = colors;
  37667. }
  37668. return vertexData;
  37669. };
  37670. /**
  37671. * Creates the VertexData for a torus
  37672. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37673. * * diameter the diameter of the torus, optional default 1
  37674. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37675. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37676. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37677. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37678. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37679. * @returns the VertexData of the torus
  37680. */
  37681. VertexData.CreateTorus = function (options) {
  37682. var indices = [];
  37683. var positions = [];
  37684. var normals = [];
  37685. var uvs = [];
  37686. var diameter = options.diameter || 1;
  37687. var thickness = options.thickness || 0.5;
  37688. var tessellation = options.tessellation || 16;
  37689. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37690. var stride = tessellation + 1;
  37691. for (var i = 0; i <= tessellation; i++) {
  37692. var u = i / tessellation;
  37693. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37694. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37695. for (var j = 0; j <= tessellation; j++) {
  37696. var v = 1 - j / tessellation;
  37697. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37698. var dx = Math.cos(innerAngle);
  37699. var dy = Math.sin(innerAngle);
  37700. // Create a vertex.
  37701. var normal = new BABYLON.Vector3(dx, dy, 0);
  37702. var position = normal.scale(thickness / 2);
  37703. var textureCoordinate = new BABYLON.Vector2(u, v);
  37704. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37705. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37706. positions.push(position.x, position.y, position.z);
  37707. normals.push(normal.x, normal.y, normal.z);
  37708. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37709. // And create indices for two triangles.
  37710. var nextI = (i + 1) % stride;
  37711. var nextJ = (j + 1) % stride;
  37712. indices.push(i * stride + j);
  37713. indices.push(i * stride + nextJ);
  37714. indices.push(nextI * stride + j);
  37715. indices.push(i * stride + nextJ);
  37716. indices.push(nextI * stride + nextJ);
  37717. indices.push(nextI * stride + j);
  37718. }
  37719. }
  37720. // Sides
  37721. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37722. // Result
  37723. var vertexData = new VertexData();
  37724. vertexData.indices = indices;
  37725. vertexData.positions = positions;
  37726. vertexData.normals = normals;
  37727. vertexData.uvs = uvs;
  37728. return vertexData;
  37729. };
  37730. /**
  37731. * Creates the VertexData of the LineSystem
  37732. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37733. * - lines an array of lines, each line being an array of successive Vector3
  37734. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37735. * @returns the VertexData of the LineSystem
  37736. */
  37737. VertexData.CreateLineSystem = function (options) {
  37738. var indices = [];
  37739. var positions = [];
  37740. var lines = options.lines;
  37741. var colors = options.colors;
  37742. var vertexColors = [];
  37743. var idx = 0;
  37744. for (var l = 0; l < lines.length; l++) {
  37745. var points = lines[l];
  37746. for (var index = 0; index < points.length; index++) {
  37747. positions.push(points[index].x, points[index].y, points[index].z);
  37748. if (colors) {
  37749. var color = colors[l];
  37750. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37751. }
  37752. if (index > 0) {
  37753. indices.push(idx - 1);
  37754. indices.push(idx);
  37755. }
  37756. idx++;
  37757. }
  37758. }
  37759. var vertexData = new VertexData();
  37760. vertexData.indices = indices;
  37761. vertexData.positions = positions;
  37762. if (colors) {
  37763. vertexData.colors = vertexColors;
  37764. }
  37765. return vertexData;
  37766. };
  37767. /**
  37768. * Create the VertexData for a DashedLines
  37769. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37770. * - points an array successive Vector3
  37771. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37772. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37773. * - dashNb the intended total number of dashes, optional, default 200
  37774. * @returns the VertexData for the DashedLines
  37775. */
  37776. VertexData.CreateDashedLines = function (options) {
  37777. var dashSize = options.dashSize || 3;
  37778. var gapSize = options.gapSize || 1;
  37779. var dashNb = options.dashNb || 200;
  37780. var points = options.points;
  37781. var positions = new Array();
  37782. var indices = new Array();
  37783. var curvect = BABYLON.Vector3.Zero();
  37784. var lg = 0;
  37785. var nb = 0;
  37786. var shft = 0;
  37787. var dashshft = 0;
  37788. var curshft = 0;
  37789. var idx = 0;
  37790. var i = 0;
  37791. for (i = 0; i < points.length - 1; i++) {
  37792. points[i + 1].subtractToRef(points[i], curvect);
  37793. lg += curvect.length();
  37794. }
  37795. shft = lg / dashNb;
  37796. dashshft = dashSize * shft / (dashSize + gapSize);
  37797. for (i = 0; i < points.length - 1; i++) {
  37798. points[i + 1].subtractToRef(points[i], curvect);
  37799. nb = Math.floor(curvect.length() / shft);
  37800. curvect.normalize();
  37801. for (var j = 0; j < nb; j++) {
  37802. curshft = shft * j;
  37803. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37804. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37805. indices.push(idx, idx + 1);
  37806. idx += 2;
  37807. }
  37808. }
  37809. // Result
  37810. var vertexData = new VertexData();
  37811. vertexData.positions = positions;
  37812. vertexData.indices = indices;
  37813. return vertexData;
  37814. };
  37815. /**
  37816. * Creates the VertexData for a Ground
  37817. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37818. * - width the width (x direction) of the ground, optional, default 1
  37819. * - height the height (z direction) of the ground, optional, default 1
  37820. * - subdivisions the number of subdivisions per side, optional, default 1
  37821. * @returns the VertexData of the Ground
  37822. */
  37823. VertexData.CreateGround = function (options) {
  37824. var indices = [];
  37825. var positions = [];
  37826. var normals = [];
  37827. var uvs = [];
  37828. var row, col;
  37829. var width = options.width || 1;
  37830. var height = options.height || 1;
  37831. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37832. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37833. for (row = 0; row <= subdivisionsY; row++) {
  37834. for (col = 0; col <= subdivisionsX; col++) {
  37835. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37836. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37837. positions.push(position.x, position.y, position.z);
  37838. normals.push(normal.x, normal.y, normal.z);
  37839. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37840. }
  37841. }
  37842. for (row = 0; row < subdivisionsY; row++) {
  37843. for (col = 0; col < subdivisionsX; col++) {
  37844. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37845. indices.push(col + 1 + row * (subdivisionsX + 1));
  37846. indices.push(col + row * (subdivisionsX + 1));
  37847. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37848. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37849. indices.push(col + row * (subdivisionsX + 1));
  37850. }
  37851. }
  37852. // Result
  37853. var vertexData = new VertexData();
  37854. vertexData.indices = indices;
  37855. vertexData.positions = positions;
  37856. vertexData.normals = normals;
  37857. vertexData.uvs = uvs;
  37858. return vertexData;
  37859. };
  37860. /**
  37861. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37862. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37863. * * xmin the ground minimum X coordinate, optional, default -1
  37864. * * zmin the ground minimum Z coordinate, optional, default -1
  37865. * * xmax the ground maximum X coordinate, optional, default 1
  37866. * * zmax the ground maximum Z coordinate, optional, default 1
  37867. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37868. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37869. * @returns the VertexData of the TiledGround
  37870. */
  37871. VertexData.CreateTiledGround = function (options) {
  37872. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37873. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37874. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37875. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37876. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37877. var precision = options.precision || { w: 1, h: 1 };
  37878. var indices = new Array();
  37879. var positions = new Array();
  37880. var normals = new Array();
  37881. var uvs = new Array();
  37882. var row, col, tileRow, tileCol;
  37883. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37884. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37885. precision.w = (precision.w < 1) ? 1 : precision.w;
  37886. precision.h = (precision.h < 1) ? 1 : precision.h;
  37887. var tileSize = {
  37888. 'w': (xmax - xmin) / subdivisions.w,
  37889. 'h': (zmax - zmin) / subdivisions.h
  37890. };
  37891. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37892. // Indices
  37893. var base = positions.length / 3;
  37894. var rowLength = precision.w + 1;
  37895. for (row = 0; row < precision.h; row++) {
  37896. for (col = 0; col < precision.w; col++) {
  37897. var square = [
  37898. base + col + row * rowLength,
  37899. base + (col + 1) + row * rowLength,
  37900. base + (col + 1) + (row + 1) * rowLength,
  37901. base + col + (row + 1) * rowLength
  37902. ];
  37903. indices.push(square[1]);
  37904. indices.push(square[2]);
  37905. indices.push(square[3]);
  37906. indices.push(square[0]);
  37907. indices.push(square[1]);
  37908. indices.push(square[3]);
  37909. }
  37910. }
  37911. // Position, normals and uvs
  37912. var position = BABYLON.Vector3.Zero();
  37913. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37914. for (row = 0; row <= precision.h; row++) {
  37915. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37916. for (col = 0; col <= precision.w; col++) {
  37917. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37918. position.y = 0;
  37919. positions.push(position.x, position.y, position.z);
  37920. normals.push(normal.x, normal.y, normal.z);
  37921. uvs.push(col / precision.w, row / precision.h);
  37922. }
  37923. }
  37924. }
  37925. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37926. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37927. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37928. }
  37929. }
  37930. // Result
  37931. var vertexData = new VertexData();
  37932. vertexData.indices = indices;
  37933. vertexData.positions = positions;
  37934. vertexData.normals = normals;
  37935. vertexData.uvs = uvs;
  37936. return vertexData;
  37937. };
  37938. /**
  37939. * Creates the VertexData of the Ground designed from a heightmap
  37940. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37941. * * width the width (x direction) of the ground
  37942. * * height the height (z direction) of the ground
  37943. * * subdivisions the number of subdivisions per side
  37944. * * minHeight the minimum altitude on the ground, optional, default 0
  37945. * * maxHeight the maximum altitude on the ground, optional default 1
  37946. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37947. * * buffer the array holding the image color data
  37948. * * bufferWidth the width of image
  37949. * * bufferHeight the height of image
  37950. * @returns the VertexData of the Ground designed from a heightmap
  37951. */
  37952. VertexData.CreateGroundFromHeightMap = function (options) {
  37953. var indices = [];
  37954. var positions = [];
  37955. var normals = [];
  37956. var uvs = [];
  37957. var row, col;
  37958. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37959. // Vertices
  37960. for (row = 0; row <= options.subdivisions; row++) {
  37961. for (col = 0; col <= options.subdivisions; col++) {
  37962. 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));
  37963. // Compute height
  37964. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37965. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37966. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37967. var r = options.buffer[pos] / 255.0;
  37968. var g = options.buffer[pos + 1] / 255.0;
  37969. var b = options.buffer[pos + 2] / 255.0;
  37970. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37971. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37972. // Add vertex
  37973. positions.push(position.x, position.y, position.z);
  37974. normals.push(0, 0, 0);
  37975. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37976. }
  37977. }
  37978. // Indices
  37979. for (row = 0; row < options.subdivisions; row++) {
  37980. for (col = 0; col < options.subdivisions; col++) {
  37981. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37982. indices.push(col + 1 + row * (options.subdivisions + 1));
  37983. indices.push(col + row * (options.subdivisions + 1));
  37984. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37985. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37986. indices.push(col + row * (options.subdivisions + 1));
  37987. }
  37988. }
  37989. // Normals
  37990. VertexData.ComputeNormals(positions, indices, normals);
  37991. // Result
  37992. var vertexData = new VertexData();
  37993. vertexData.indices = indices;
  37994. vertexData.positions = positions;
  37995. vertexData.normals = normals;
  37996. vertexData.uvs = uvs;
  37997. return vertexData;
  37998. };
  37999. /**
  38000. * Creates the VertexData for a Plane
  38001. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38002. * * size sets the width and height of the plane to the value of size, optional default 1
  38003. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38004. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38005. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38006. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38007. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38008. * @returns the VertexData of the box
  38009. */
  38010. VertexData.CreatePlane = function (options) {
  38011. var indices = [];
  38012. var positions = [];
  38013. var normals = [];
  38014. var uvs = [];
  38015. var width = options.width || options.size || 1;
  38016. var height = options.height || options.size || 1;
  38017. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38018. // Vertices
  38019. var halfWidth = width / 2.0;
  38020. var halfHeight = height / 2.0;
  38021. positions.push(-halfWidth, -halfHeight, 0);
  38022. normals.push(0, 0, -1.0);
  38023. uvs.push(0.0, 0.0);
  38024. positions.push(halfWidth, -halfHeight, 0);
  38025. normals.push(0, 0, -1.0);
  38026. uvs.push(1.0, 0.0);
  38027. positions.push(halfWidth, halfHeight, 0);
  38028. normals.push(0, 0, -1.0);
  38029. uvs.push(1.0, 1.0);
  38030. positions.push(-halfWidth, halfHeight, 0);
  38031. normals.push(0, 0, -1.0);
  38032. uvs.push(0.0, 1.0);
  38033. // Indices
  38034. indices.push(0);
  38035. indices.push(1);
  38036. indices.push(2);
  38037. indices.push(0);
  38038. indices.push(2);
  38039. indices.push(3);
  38040. // Sides
  38041. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38042. // Result
  38043. var vertexData = new VertexData();
  38044. vertexData.indices = indices;
  38045. vertexData.positions = positions;
  38046. vertexData.normals = normals;
  38047. vertexData.uvs = uvs;
  38048. return vertexData;
  38049. };
  38050. /**
  38051. * Creates the VertexData of the Disc or regular Polygon
  38052. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38053. * * radius the radius of the disc, optional default 0.5
  38054. * * tessellation the number of polygon sides, optional, default 64
  38055. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  38056. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38057. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38058. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38059. * @returns the VertexData of the box
  38060. */
  38061. VertexData.CreateDisc = function (options) {
  38062. var positions = new Array();
  38063. var indices = new Array();
  38064. var normals = new Array();
  38065. var uvs = new Array();
  38066. var radius = options.radius || 0.5;
  38067. var tessellation = options.tessellation || 64;
  38068. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38069. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38070. // positions and uvs
  38071. positions.push(0, 0, 0); // disc center first
  38072. uvs.push(0.5, 0.5);
  38073. var theta = Math.PI * 2 * arc;
  38074. var step = theta / tessellation;
  38075. for (var a = 0; a < theta; a += step) {
  38076. var x = Math.cos(a);
  38077. var y = Math.sin(a);
  38078. var u = (x + 1) / 2;
  38079. var v = (1 - y) / 2;
  38080. positions.push(radius * x, radius * y, 0);
  38081. uvs.push(u, v);
  38082. }
  38083. if (arc === 1) {
  38084. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38085. uvs.push(uvs[2], uvs[3]);
  38086. }
  38087. //indices
  38088. var vertexNb = positions.length / 3;
  38089. for (var i = 1; i < vertexNb - 1; i++) {
  38090. indices.push(i + 1, 0, i);
  38091. }
  38092. // result
  38093. VertexData.ComputeNormals(positions, indices, normals);
  38094. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38095. var vertexData = new VertexData();
  38096. vertexData.indices = indices;
  38097. vertexData.positions = positions;
  38098. vertexData.normals = normals;
  38099. vertexData.uvs = uvs;
  38100. return vertexData;
  38101. };
  38102. /**
  38103. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38104. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38105. * @param polygon a mesh built from polygonTriangulation.build()
  38106. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38107. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38108. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38109. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38110. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38111. * @returns the VertexData of the Polygon
  38112. */
  38113. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38114. var faceUV = fUV || new Array(3);
  38115. var faceColors = fColors;
  38116. var colors = [];
  38117. // default face colors and UV if undefined
  38118. for (var f = 0; f < 3; f++) {
  38119. if (faceUV[f] === undefined) {
  38120. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38121. }
  38122. if (faceColors && faceColors[f] === undefined) {
  38123. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38124. }
  38125. }
  38126. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38127. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38128. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38129. var indices = polygon.getIndices();
  38130. // set face colours and textures
  38131. var idx = 0;
  38132. var face = 0;
  38133. for (var index = 0; index < normals.length; index += 3) {
  38134. //Edge Face no. 1
  38135. if (Math.abs(normals[index + 1]) < 0.001) {
  38136. face = 1;
  38137. }
  38138. //Top Face no. 0
  38139. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38140. face = 0;
  38141. }
  38142. //Bottom Face no. 2
  38143. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38144. face = 2;
  38145. }
  38146. idx = index / 3;
  38147. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38148. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38149. if (faceColors) {
  38150. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38151. }
  38152. }
  38153. // sides
  38154. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38155. // Result
  38156. var vertexData = new VertexData();
  38157. vertexData.indices = indices;
  38158. vertexData.positions = positions;
  38159. vertexData.normals = normals;
  38160. vertexData.uvs = uvs;
  38161. if (faceColors) {
  38162. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38163. vertexData.colors = totalColors;
  38164. }
  38165. return vertexData;
  38166. };
  38167. /**
  38168. * Creates the VertexData of the IcoSphere
  38169. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38170. * * radius the radius of the IcoSphere, optional default 1
  38171. * * radiusX allows stretching in the x direction, optional, default radius
  38172. * * radiusY allows stretching in the y direction, optional, default radius
  38173. * * radiusZ allows stretching in the z direction, optional, default radius
  38174. * * flat when true creates a flat shaded mesh, optional, default true
  38175. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38176. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38177. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38178. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38179. * @returns the VertexData of the IcoSphere
  38180. */
  38181. VertexData.CreateIcoSphere = function (options) {
  38182. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38183. var radius = options.radius || 1;
  38184. var flat = (options.flat === undefined) ? true : options.flat;
  38185. var subdivisions = options.subdivisions || 4;
  38186. var radiusX = options.radiusX || radius;
  38187. var radiusY = options.radiusY || radius;
  38188. var radiusZ = options.radiusZ || radius;
  38189. var t = (1 + Math.sqrt(5)) / 2;
  38190. // 12 vertex x,y,z
  38191. var ico_vertices = [
  38192. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38193. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38194. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38195. ];
  38196. // index of 3 vertex makes a face of icopshere
  38197. var ico_indices = [
  38198. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38199. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38200. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38201. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38202. ];
  38203. // vertex for uv have aliased position, not for UV
  38204. var vertices_unalias_id = [
  38205. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38206. // vertex alias
  38207. 0,
  38208. 2,
  38209. 3,
  38210. 3,
  38211. 3,
  38212. 4,
  38213. 7,
  38214. 8,
  38215. 9,
  38216. 9,
  38217. 10,
  38218. 11 // 23: B + 12
  38219. ];
  38220. // uv as integer step (not pixels !)
  38221. var ico_vertexuv = [
  38222. 5, 1, 3, 1, 6, 4, 0, 0,
  38223. 5, 3, 4, 2, 2, 2, 4, 0,
  38224. 2, 0, 1, 1, 6, 0, 6, 2,
  38225. // vertex alias (for same vertex on different faces)
  38226. 0, 4,
  38227. 3, 3,
  38228. 4, 4,
  38229. 3, 1,
  38230. 4, 2,
  38231. 4, 4,
  38232. 0, 2,
  38233. 1, 1,
  38234. 2, 2,
  38235. 3, 3,
  38236. 1, 3,
  38237. 2, 4 // 23: B + 12
  38238. ];
  38239. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38240. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38241. // First island of uv mapping
  38242. // v = 4h 3+ 2
  38243. // v = 3h 9+ 4
  38244. // v = 2h 9+ 5 B
  38245. // v = 1h 9 1 0
  38246. // v = 0h 3 8 7 A
  38247. // u = 0 1 2 3 4 5 6 *a
  38248. // Second island of uv mapping
  38249. // v = 4h 0+ B+ 4+
  38250. // v = 3h A+ 2+
  38251. // v = 2h 7+ 6 3+
  38252. // v = 1h 8+ 3+
  38253. // v = 0h
  38254. // u = 0 1 2 3 4 5 6 *a
  38255. // Face layout on texture UV mapping
  38256. // ============
  38257. // \ 4 /\ 16 / ======
  38258. // \ / \ / /\ 11 /
  38259. // \/ 7 \/ / \ /
  38260. // ======= / 10 \/
  38261. // /\ 17 /\ =======
  38262. // / \ / \ \ 15 /\
  38263. // / 8 \/ 12 \ \ / \
  38264. // ============ \/ 6 \
  38265. // \ 18 /\ ============
  38266. // \ / \ \ 5 /\ 0 /
  38267. // \/ 13 \ \ / \ /
  38268. // ======= \/ 1 \/
  38269. // =============
  38270. // /\ 19 /\ 2 /\
  38271. // / \ / \ / \
  38272. // / 14 \/ 9 \/ 3 \
  38273. // ===================
  38274. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38275. var ustep = 138 / 1024;
  38276. var vstep = 239 / 1024;
  38277. var uoffset = 60 / 1024;
  38278. var voffset = 26 / 1024;
  38279. // Second island should have margin, not to touch the first island
  38280. // avoid any borderline artefact in pixel rounding
  38281. var island_u_offset = -40 / 1024;
  38282. var island_v_offset = +20 / 1024;
  38283. // face is either island 0 or 1 :
  38284. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38285. var island = [
  38286. 0, 0, 0, 0, 1,
  38287. 0, 0, 1, 1, 0,
  38288. 0, 0, 1, 1, 0,
  38289. 0, 1, 1, 1, 0 // 15 - 19
  38290. ];
  38291. var indices = new Array();
  38292. var positions = new Array();
  38293. var normals = new Array();
  38294. var uvs = new Array();
  38295. var current_indice = 0;
  38296. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38297. var face_vertex_pos = new Array(3);
  38298. var face_vertex_uv = new Array(3);
  38299. var v012;
  38300. for (v012 = 0; v012 < 3; v012++) {
  38301. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38302. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38303. }
  38304. // create all with normals
  38305. for (var face = 0; face < 20; face++) {
  38306. // 3 vertex per face
  38307. for (v012 = 0; v012 < 3; v012++) {
  38308. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38309. var v_id = ico_indices[3 * face + v012];
  38310. // vertex have 3D position (x,y,z)
  38311. 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]);
  38312. // Normalize to get normal, then scale to radius
  38313. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38314. // uv Coordinates from vertex ID
  38315. 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);
  38316. }
  38317. // Subdivide the face (interpolate pos, norm, uv)
  38318. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38319. // - norm is linear interpolation of vertex corner normal
  38320. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38321. // - uv is linear interpolation
  38322. //
  38323. // Topology is as below for sub-divide by 2
  38324. // vertex shown as v0,v1,v2
  38325. // interp index is i1 to progress in range [v0,v1[
  38326. // interp index is i2 to progress in range [v0,v2[
  38327. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38328. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38329. //
  38330. //
  38331. // i2 v2
  38332. // ^ ^
  38333. // / / \
  38334. // / / \
  38335. // / / \
  38336. // / / (0,1) \
  38337. // / #---------\
  38338. // / / \ (0,0)'/ \
  38339. // / / \ / \
  38340. // / / \ / \
  38341. // / / (0,0) \ / (1,0) \
  38342. // / #---------#---------\
  38343. // v0 v1
  38344. //
  38345. // --------------------> i1
  38346. //
  38347. // interp of (i1,i2):
  38348. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38349. // along i1 : lerp(x0,x1, i1/(S-i2))
  38350. //
  38351. // centroid of triangle is needed to get help normal computation
  38352. // (c1,c2) are used for centroid location
  38353. var interp_vertex = function (i1, i2, c1, c2) {
  38354. // vertex is interpolated from
  38355. // - face_vertex_pos[0..2]
  38356. // - face_vertex_uv[0..2]
  38357. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38358. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38359. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38360. pos_interp.normalize();
  38361. var vertex_normal;
  38362. if (flat) {
  38363. // in flat mode, recalculate normal as face centroid normal
  38364. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38365. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38366. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38367. }
  38368. else {
  38369. // in smooth mode, recalculate normal from each single vertex position
  38370. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38371. }
  38372. // Vertex normal need correction due to X,Y,Z radius scaling
  38373. vertex_normal.x /= radiusX;
  38374. vertex_normal.y /= radiusY;
  38375. vertex_normal.z /= radiusZ;
  38376. vertex_normal.normalize();
  38377. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38378. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38379. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38380. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38381. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38382. uvs.push(uv_interp.x, uv_interp.y);
  38383. // push each vertex has member of a face
  38384. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38385. indices.push(current_indice);
  38386. current_indice++;
  38387. };
  38388. for (var i2 = 0; i2 < subdivisions; i2++) {
  38389. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38390. // face : (i1,i2) for /\ :
  38391. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38392. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38393. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38394. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38395. if (i1 + i2 + 1 < subdivisions) {
  38396. // face : (i1,i2)' for \/ :
  38397. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38398. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38399. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38400. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38401. }
  38402. }
  38403. }
  38404. }
  38405. // Sides
  38406. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38407. // Result
  38408. var vertexData = new VertexData();
  38409. vertexData.indices = indices;
  38410. vertexData.positions = positions;
  38411. vertexData.normals = normals;
  38412. vertexData.uvs = uvs;
  38413. return vertexData;
  38414. };
  38415. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38416. /**
  38417. * Creates the VertexData for a Polyhedron
  38418. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38419. * * type provided types are:
  38420. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38421. * * 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)
  38422. * * size the size of the IcoSphere, optional default 1
  38423. * * sizeX allows stretching in the x direction, optional, default size
  38424. * * sizeY allows stretching in the y direction, optional, default size
  38425. * * sizeZ allows stretching in the z direction, optional, default size
  38426. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38427. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38428. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38429. * * flat when true creates a flat shaded mesh, optional, default true
  38430. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38431. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38432. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38433. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38434. * @returns the VertexData of the Polyhedron
  38435. */
  38436. VertexData.CreatePolyhedron = function (options) {
  38437. // provided polyhedron types :
  38438. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38439. // 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)
  38440. var polyhedra = [];
  38441. 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]] };
  38442. 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]] };
  38443. polyhedra[2] = {
  38444. 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]],
  38445. 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]]
  38446. };
  38447. polyhedra[3] = {
  38448. 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]],
  38449. 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]]
  38450. };
  38451. polyhedra[4] = {
  38452. 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]],
  38453. 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]]
  38454. };
  38455. 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]] };
  38456. 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]] };
  38457. 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]] };
  38458. 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]] };
  38459. 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]] };
  38460. 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]] };
  38461. 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]] };
  38462. 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]] };
  38463. 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]] };
  38464. polyhedra[14] = {
  38465. 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]],
  38466. 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]]
  38467. };
  38468. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38469. var size = options.size;
  38470. var sizeX = options.sizeX || size || 1;
  38471. var sizeY = options.sizeY || size || 1;
  38472. var sizeZ = options.sizeZ || size || 1;
  38473. var data = options.custom || polyhedra[type];
  38474. var nbfaces = data.face.length;
  38475. var faceUV = options.faceUV || new Array(nbfaces);
  38476. var faceColors = options.faceColors;
  38477. var flat = (options.flat === undefined) ? true : options.flat;
  38478. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38479. var positions = new Array();
  38480. var indices = new Array();
  38481. var normals = new Array();
  38482. var uvs = new Array();
  38483. var colors = new Array();
  38484. var index = 0;
  38485. var faceIdx = 0; // face cursor in the array "indexes"
  38486. var indexes = new Array();
  38487. var i = 0;
  38488. var f = 0;
  38489. var u, v, ang, x, y, tmp;
  38490. // default face colors and UV if undefined
  38491. if (flat) {
  38492. for (f = 0; f < nbfaces; f++) {
  38493. if (faceColors && faceColors[f] === undefined) {
  38494. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38495. }
  38496. if (faceUV && faceUV[f] === undefined) {
  38497. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38498. }
  38499. }
  38500. }
  38501. if (!flat) {
  38502. for (i = 0; i < data.vertex.length; i++) {
  38503. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38504. uvs.push(0, 0);
  38505. }
  38506. for (f = 0; f < nbfaces; f++) {
  38507. for (i = 0; i < data.face[f].length - 2; i++) {
  38508. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38509. }
  38510. }
  38511. }
  38512. else {
  38513. for (f = 0; f < nbfaces; f++) {
  38514. var fl = data.face[f].length; // number of vertices of the current face
  38515. ang = 2 * Math.PI / fl;
  38516. x = 0.5 * Math.tan(ang / 2);
  38517. y = 0.5;
  38518. // positions, uvs, colors
  38519. for (i = 0; i < fl; i++) {
  38520. // positions
  38521. 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);
  38522. indexes.push(index);
  38523. index++;
  38524. // uvs
  38525. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38526. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38527. uvs.push(u, v);
  38528. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38529. y = x * Math.sin(ang) + y * Math.cos(ang);
  38530. x = tmp;
  38531. // colors
  38532. if (faceColors) {
  38533. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38534. }
  38535. }
  38536. // indices from indexes
  38537. for (i = 0; i < fl - 2; i++) {
  38538. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38539. }
  38540. faceIdx += fl;
  38541. }
  38542. }
  38543. VertexData.ComputeNormals(positions, indices, normals);
  38544. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38545. var vertexData = new VertexData();
  38546. vertexData.positions = positions;
  38547. vertexData.indices = indices;
  38548. vertexData.normals = normals;
  38549. vertexData.uvs = uvs;
  38550. if (faceColors && flat) {
  38551. vertexData.colors = colors;
  38552. }
  38553. return vertexData;
  38554. };
  38555. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38556. /**
  38557. * Creates the VertexData for a TorusKnot
  38558. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38559. * * radius the radius of the torus knot, optional, default 2
  38560. * * tube the thickness of the tube, optional, default 0.5
  38561. * * radialSegments the number of sides on each tube segments, optional, default 32
  38562. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38563. * * p the number of windings around the z axis, optional, default 2
  38564. * * q the number of windings around the x axis, optional, default 3
  38565. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38566. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38567. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38568. * @returns the VertexData of the Torus Knot
  38569. */
  38570. VertexData.CreateTorusKnot = function (options) {
  38571. var indices = new Array();
  38572. var positions = new Array();
  38573. var normals = new Array();
  38574. var uvs = new Array();
  38575. var radius = options.radius || 2;
  38576. var tube = options.tube || 0.5;
  38577. var radialSegments = options.radialSegments || 32;
  38578. var tubularSegments = options.tubularSegments || 32;
  38579. var p = options.p || 2;
  38580. var q = options.q || 3;
  38581. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38582. // Helper
  38583. var getPos = function (angle) {
  38584. var cu = Math.cos(angle);
  38585. var su = Math.sin(angle);
  38586. var quOverP = q / p * angle;
  38587. var cs = Math.cos(quOverP);
  38588. var tx = radius * (2 + cs) * 0.5 * cu;
  38589. var ty = radius * (2 + cs) * su * 0.5;
  38590. var tz = radius * Math.sin(quOverP) * 0.5;
  38591. return new BABYLON.Vector3(tx, ty, tz);
  38592. };
  38593. // Vertices
  38594. var i;
  38595. var j;
  38596. for (i = 0; i <= radialSegments; i++) {
  38597. var modI = i % radialSegments;
  38598. var u = modI / radialSegments * 2 * p * Math.PI;
  38599. var p1 = getPos(u);
  38600. var p2 = getPos(u + 0.01);
  38601. var tang = p2.subtract(p1);
  38602. var n = p2.add(p1);
  38603. var bitan = BABYLON.Vector3.Cross(tang, n);
  38604. n = BABYLON.Vector3.Cross(bitan, tang);
  38605. bitan.normalize();
  38606. n.normalize();
  38607. for (j = 0; j < tubularSegments; j++) {
  38608. var modJ = j % tubularSegments;
  38609. var v = modJ / tubularSegments * 2 * Math.PI;
  38610. var cx = -tube * Math.cos(v);
  38611. var cy = tube * Math.sin(v);
  38612. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38613. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38614. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38615. uvs.push(i / radialSegments);
  38616. uvs.push(j / tubularSegments);
  38617. }
  38618. }
  38619. for (i = 0; i < radialSegments; i++) {
  38620. for (j = 0; j < tubularSegments; j++) {
  38621. var jNext = (j + 1) % tubularSegments;
  38622. var a = i * tubularSegments + j;
  38623. var b = (i + 1) * tubularSegments + j;
  38624. var c = (i + 1) * tubularSegments + jNext;
  38625. var d = i * tubularSegments + jNext;
  38626. indices.push(d);
  38627. indices.push(b);
  38628. indices.push(a);
  38629. indices.push(d);
  38630. indices.push(c);
  38631. indices.push(b);
  38632. }
  38633. }
  38634. // Normals
  38635. VertexData.ComputeNormals(positions, indices, normals);
  38636. // Sides
  38637. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38638. // Result
  38639. var vertexData = new VertexData();
  38640. vertexData.indices = indices;
  38641. vertexData.positions = positions;
  38642. vertexData.normals = normals;
  38643. vertexData.uvs = uvs;
  38644. return vertexData;
  38645. };
  38646. // Tools
  38647. /**
  38648. * Compute normals for given positions and indices
  38649. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38650. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38651. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38652. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38653. * * facetNormals : optional array of facet normals (vector3)
  38654. * * facetPositions : optional array of facet positions (vector3)
  38655. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38656. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38657. * * bInfo : optional bounding info, required for facetPartitioning computation
  38658. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38659. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38660. * * useRightHandedSystem: optional boolean to for right handed system computation
  38661. * * depthSort : optional boolean to enable the facet depth sort computation
  38662. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38663. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38664. */
  38665. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38666. // temporary scalar variables
  38667. var index = 0; // facet index
  38668. var p1p2x = 0.0; // p1p2 vector x coordinate
  38669. var p1p2y = 0.0; // p1p2 vector y coordinate
  38670. var p1p2z = 0.0; // p1p2 vector z coordinate
  38671. var p3p2x = 0.0; // p3p2 vector x coordinate
  38672. var p3p2y = 0.0; // p3p2 vector y coordinate
  38673. var p3p2z = 0.0; // p3p2 vector z coordinate
  38674. var faceNormalx = 0.0; // facet normal x coordinate
  38675. var faceNormaly = 0.0; // facet normal y coordinate
  38676. var faceNormalz = 0.0; // facet normal z coordinate
  38677. var length = 0.0; // facet normal length before normalization
  38678. var v1x = 0; // vector1 x index in the positions array
  38679. var v1y = 0; // vector1 y index in the positions array
  38680. var v1z = 0; // vector1 z index in the positions array
  38681. var v2x = 0; // vector2 x index in the positions array
  38682. var v2y = 0; // vector2 y index in the positions array
  38683. var v2z = 0; // vector2 z index in the positions array
  38684. var v3x = 0; // vector3 x index in the positions array
  38685. var v3y = 0; // vector3 y index in the positions array
  38686. var v3z = 0; // vector3 z index in the positions array
  38687. var computeFacetNormals = false;
  38688. var computeFacetPositions = false;
  38689. var computeFacetPartitioning = false;
  38690. var computeDepthSort = false;
  38691. var faceNormalSign = 1;
  38692. var ratio = 0;
  38693. var distanceTo = null;
  38694. if (options) {
  38695. computeFacetNormals = (options.facetNormals) ? true : false;
  38696. computeFacetPositions = (options.facetPositions) ? true : false;
  38697. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38698. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38699. ratio = options.ratio || 0;
  38700. computeDepthSort = (options.depthSort) ? true : false;
  38701. distanceTo = (options.distanceTo);
  38702. if (computeDepthSort) {
  38703. if (distanceTo === undefined) {
  38704. distanceTo = BABYLON.Vector3.Zero();
  38705. }
  38706. var depthSortedFacets = options.depthSortedFacets;
  38707. }
  38708. }
  38709. // facetPartitioning reinit if needed
  38710. var xSubRatio = 0;
  38711. var ySubRatio = 0;
  38712. var zSubRatio = 0;
  38713. var subSq = 0;
  38714. if (computeFacetPartitioning && options && options.bbSize) {
  38715. var ox = 0; // X partitioning index for facet position
  38716. var oy = 0; // Y partinioning index for facet position
  38717. var oz = 0; // Z partinioning index for facet position
  38718. var b1x = 0; // X partitioning index for facet v1 vertex
  38719. var b1y = 0; // Y partitioning index for facet v1 vertex
  38720. var b1z = 0; // z partitioning index for facet v1 vertex
  38721. var b2x = 0; // X partitioning index for facet v2 vertex
  38722. var b2y = 0; // Y partitioning index for facet v2 vertex
  38723. var b2z = 0; // Z partitioning index for facet v2 vertex
  38724. var b3x = 0; // X partitioning index for facet v3 vertex
  38725. var b3y = 0; // Y partitioning index for facet v3 vertex
  38726. var b3z = 0; // Z partitioning index for facet v3 vertex
  38727. var block_idx_o = 0; // facet barycenter block index
  38728. var block_idx_v1 = 0; // v1 vertex block index
  38729. var block_idx_v2 = 0; // v2 vertex block index
  38730. var block_idx_v3 = 0; // v3 vertex block index
  38731. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38732. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38733. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38734. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38735. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38736. subSq = options.subDiv.max * options.subDiv.max;
  38737. options.facetPartitioning.length = 0;
  38738. }
  38739. // reset the normals
  38740. for (index = 0; index < positions.length; index++) {
  38741. normals[index] = 0.0;
  38742. }
  38743. // Loop : 1 indice triplet = 1 facet
  38744. var nbFaces = (indices.length / 3) | 0;
  38745. for (index = 0; index < nbFaces; index++) {
  38746. // get the indexes of the coordinates of each vertex of the facet
  38747. v1x = indices[index * 3] * 3;
  38748. v1y = v1x + 1;
  38749. v1z = v1x + 2;
  38750. v2x = indices[index * 3 + 1] * 3;
  38751. v2y = v2x + 1;
  38752. v2z = v2x + 2;
  38753. v3x = indices[index * 3 + 2] * 3;
  38754. v3y = v3x + 1;
  38755. v3z = v3x + 2;
  38756. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38757. p1p2y = positions[v1y] - positions[v2y];
  38758. p1p2z = positions[v1z] - positions[v2z];
  38759. p3p2x = positions[v3x] - positions[v2x];
  38760. p3p2y = positions[v3y] - positions[v2y];
  38761. p3p2z = positions[v3z] - positions[v2z];
  38762. // compute the face normal with the cross product
  38763. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38764. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38765. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38766. // normalize this normal and store it in the array facetData
  38767. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38768. length = (length === 0) ? 1.0 : length;
  38769. faceNormalx /= length;
  38770. faceNormaly /= length;
  38771. faceNormalz /= length;
  38772. if (computeFacetNormals && options) {
  38773. options.facetNormals[index].x = faceNormalx;
  38774. options.facetNormals[index].y = faceNormaly;
  38775. options.facetNormals[index].z = faceNormalz;
  38776. }
  38777. if (computeFacetPositions && options) {
  38778. // compute and the facet barycenter coordinates in the array facetPositions
  38779. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38780. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38781. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38782. }
  38783. if (computeFacetPartitioning && options) {
  38784. // store the facet indexes in arrays in the main facetPartitioning array :
  38785. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38786. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38787. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38788. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38789. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38790. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38791. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38792. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38793. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38794. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38795. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38796. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38797. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38798. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38799. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38800. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38801. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38802. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38803. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38804. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38805. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38806. // push each facet index in each block containing the vertex
  38807. options.facetPartitioning[block_idx_v1].push(index);
  38808. if (block_idx_v2 != block_idx_v1) {
  38809. options.facetPartitioning[block_idx_v2].push(index);
  38810. }
  38811. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38812. options.facetPartitioning[block_idx_v3].push(index);
  38813. }
  38814. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38815. options.facetPartitioning[block_idx_o].push(index);
  38816. }
  38817. }
  38818. if (computeDepthSort && options && options.facetPositions) {
  38819. var dsf = depthSortedFacets[index];
  38820. dsf.ind = index * 3;
  38821. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38822. }
  38823. // compute the normals anyway
  38824. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38825. normals[v1y] += faceNormaly;
  38826. normals[v1z] += faceNormalz;
  38827. normals[v2x] += faceNormalx;
  38828. normals[v2y] += faceNormaly;
  38829. normals[v2z] += faceNormalz;
  38830. normals[v3x] += faceNormalx;
  38831. normals[v3y] += faceNormaly;
  38832. normals[v3z] += faceNormalz;
  38833. }
  38834. // last normalization of each normal
  38835. for (index = 0; index < normals.length / 3; index++) {
  38836. faceNormalx = normals[index * 3];
  38837. faceNormaly = normals[index * 3 + 1];
  38838. faceNormalz = normals[index * 3 + 2];
  38839. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38840. length = (length === 0) ? 1.0 : length;
  38841. faceNormalx /= length;
  38842. faceNormaly /= length;
  38843. faceNormalz /= length;
  38844. normals[index * 3] = faceNormalx;
  38845. normals[index * 3 + 1] = faceNormaly;
  38846. normals[index * 3 + 2] = faceNormalz;
  38847. }
  38848. };
  38849. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38850. var li = indices.length;
  38851. var ln = normals.length;
  38852. var i;
  38853. var n;
  38854. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38855. switch (sideOrientation) {
  38856. case BABYLON.Mesh.FRONTSIDE:
  38857. // nothing changed
  38858. break;
  38859. case BABYLON.Mesh.BACKSIDE:
  38860. var tmp;
  38861. // indices
  38862. for (i = 0; i < li; i += 3) {
  38863. tmp = indices[i];
  38864. indices[i] = indices[i + 2];
  38865. indices[i + 2] = tmp;
  38866. }
  38867. // normals
  38868. for (n = 0; n < ln; n++) {
  38869. normals[n] = -normals[n];
  38870. }
  38871. break;
  38872. case BABYLON.Mesh.DOUBLESIDE:
  38873. // positions
  38874. var lp = positions.length;
  38875. var l = lp / 3;
  38876. for (var p = 0; p < lp; p++) {
  38877. positions[lp + p] = positions[p];
  38878. }
  38879. // indices
  38880. for (i = 0; i < li; i += 3) {
  38881. indices[i + li] = indices[i + 2] + l;
  38882. indices[i + 1 + li] = indices[i + 1] + l;
  38883. indices[i + 2 + li] = indices[i] + l;
  38884. }
  38885. // normals
  38886. for (n = 0; n < ln; n++) {
  38887. normals[ln + n] = -normals[n];
  38888. }
  38889. // uvs
  38890. var lu = uvs.length;
  38891. var u = 0;
  38892. for (u = 0; u < lu; u++) {
  38893. uvs[u + lu] = uvs[u];
  38894. }
  38895. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38896. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38897. u = 0;
  38898. for (i = 0; i < lu / 2; i++) {
  38899. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38900. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38901. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38902. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38903. u += 2;
  38904. }
  38905. break;
  38906. }
  38907. };
  38908. /**
  38909. * Applies VertexData created from the imported parameters to the geometry
  38910. * @param parsedVertexData the parsed data from an imported file
  38911. * @param geometry the geometry to apply the VertexData to
  38912. */
  38913. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38914. var vertexData = new VertexData();
  38915. // positions
  38916. var positions = parsedVertexData.positions;
  38917. if (positions) {
  38918. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38919. }
  38920. // normals
  38921. var normals = parsedVertexData.normals;
  38922. if (normals) {
  38923. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38924. }
  38925. // tangents
  38926. var tangents = parsedVertexData.tangents;
  38927. if (tangents) {
  38928. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38929. }
  38930. // uvs
  38931. var uvs = parsedVertexData.uvs;
  38932. if (uvs) {
  38933. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38934. }
  38935. // uv2s
  38936. var uv2s = parsedVertexData.uv2s;
  38937. if (uv2s) {
  38938. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38939. }
  38940. // uv3s
  38941. var uv3s = parsedVertexData.uv3s;
  38942. if (uv3s) {
  38943. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38944. }
  38945. // uv4s
  38946. var uv4s = parsedVertexData.uv4s;
  38947. if (uv4s) {
  38948. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38949. }
  38950. // uv5s
  38951. var uv5s = parsedVertexData.uv5s;
  38952. if (uv5s) {
  38953. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38954. }
  38955. // uv6s
  38956. var uv6s = parsedVertexData.uv6s;
  38957. if (uv6s) {
  38958. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38959. }
  38960. // colors
  38961. var colors = parsedVertexData.colors;
  38962. if (colors) {
  38963. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38964. }
  38965. // matricesIndices
  38966. var matricesIndices = parsedVertexData.matricesIndices;
  38967. if (matricesIndices) {
  38968. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38969. }
  38970. // matricesWeights
  38971. var matricesWeights = parsedVertexData.matricesWeights;
  38972. if (matricesWeights) {
  38973. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38974. }
  38975. // indices
  38976. var indices = parsedVertexData.indices;
  38977. if (indices) {
  38978. vertexData.indices = indices;
  38979. }
  38980. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38981. };
  38982. return VertexData;
  38983. }());
  38984. BABYLON.VertexData = VertexData;
  38985. })(BABYLON || (BABYLON = {}));
  38986. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38987. var BABYLON;
  38988. (function (BABYLON) {
  38989. /**
  38990. * Class used to store geometry data (vertex buffers + index buffer)
  38991. */
  38992. var Geometry = /** @class */ (function () {
  38993. /**
  38994. * Creates a new geometry
  38995. * @param id defines the unique ID
  38996. * @param scene defines the hosting scene
  38997. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38998. * @param updatable defines if geometry must be updatable (false by default)
  38999. * @param mesh defines the mesh that will be associated with the geometry
  39000. */
  39001. function Geometry(id, scene, vertexData, updatable, mesh) {
  39002. if (updatable === void 0) { updatable = false; }
  39003. if (mesh === void 0) { mesh = null; }
  39004. /**
  39005. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39006. */
  39007. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39008. this._totalVertices = 0;
  39009. this._isDisposed = false;
  39010. this._indexBufferIsUpdatable = false;
  39011. this.id = id;
  39012. this._engine = scene.getEngine();
  39013. this._meshes = [];
  39014. this._scene = scene;
  39015. //Init vertex buffer cache
  39016. this._vertexBuffers = {};
  39017. this._indices = [];
  39018. this._updatable = updatable;
  39019. // vertexData
  39020. if (vertexData) {
  39021. this.setAllVerticesData(vertexData, updatable);
  39022. }
  39023. else {
  39024. this._totalVertices = 0;
  39025. this._indices = [];
  39026. }
  39027. if (this._engine.getCaps().vertexArrayObject) {
  39028. this._vertexArrayObjects = {};
  39029. }
  39030. // applyToMesh
  39031. if (mesh) {
  39032. if (mesh.getClassName() === "LinesMesh") {
  39033. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39034. this._updateExtend();
  39035. }
  39036. this.applyToMesh(mesh);
  39037. mesh.computeWorldMatrix(true);
  39038. }
  39039. }
  39040. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39041. /**
  39042. * Gets or sets 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
  39043. */
  39044. get: function () {
  39045. return this._boundingBias;
  39046. },
  39047. /**
  39048. * Gets or sets 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
  39049. */
  39050. set: function (value) {
  39051. if (this._boundingBias && this._boundingBias.equals(value)) {
  39052. return;
  39053. }
  39054. this._boundingBias = value.clone();
  39055. this._updateBoundingInfo(true, null);
  39056. },
  39057. enumerable: true,
  39058. configurable: true
  39059. });
  39060. /**
  39061. * Static function used to attach a new empty geometry to a mesh
  39062. * @param mesh defines the mesh to attach the geometry to
  39063. * @returns the new {BABYLON.Geometry}
  39064. */
  39065. Geometry.CreateGeometryForMesh = function (mesh) {
  39066. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39067. geometry.applyToMesh(mesh);
  39068. return geometry;
  39069. };
  39070. Object.defineProperty(Geometry.prototype, "extend", {
  39071. /**
  39072. * Gets the current extend of the geometry
  39073. */
  39074. get: function () {
  39075. return this._extend;
  39076. },
  39077. enumerable: true,
  39078. configurable: true
  39079. });
  39080. /**
  39081. * Gets the hosting scene
  39082. * @returns the hosting {BABYLON.Scene}
  39083. */
  39084. Geometry.prototype.getScene = function () {
  39085. return this._scene;
  39086. };
  39087. /**
  39088. * Gets the hosting engine
  39089. * @returns the hosting {BABYLON.Engine}
  39090. */
  39091. Geometry.prototype.getEngine = function () {
  39092. return this._engine;
  39093. };
  39094. /**
  39095. * Defines if the geometry is ready to use
  39096. * @returns true if the geometry is ready to be used
  39097. */
  39098. Geometry.prototype.isReady = function () {
  39099. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39100. };
  39101. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39102. /**
  39103. * Gets a value indicating that the geometry should not be serialized
  39104. */
  39105. get: function () {
  39106. for (var index = 0; index < this._meshes.length; index++) {
  39107. if (!this._meshes[index].doNotSerialize) {
  39108. return false;
  39109. }
  39110. }
  39111. return true;
  39112. },
  39113. enumerable: true,
  39114. configurable: true
  39115. });
  39116. /** @hidden */
  39117. Geometry.prototype._rebuild = function () {
  39118. if (this._vertexArrayObjects) {
  39119. this._vertexArrayObjects = {};
  39120. }
  39121. // Index buffer
  39122. if (this._meshes.length !== 0 && this._indices) {
  39123. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39124. }
  39125. // Vertex buffers
  39126. for (var key in this._vertexBuffers) {
  39127. var vertexBuffer = this._vertexBuffers[key];
  39128. vertexBuffer._rebuild();
  39129. }
  39130. };
  39131. /**
  39132. * Affects all geometry data in one call
  39133. * @param vertexData defines the geometry data
  39134. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39135. */
  39136. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39137. vertexData.applyToGeometry(this, updatable);
  39138. this.notifyUpdate();
  39139. };
  39140. /**
  39141. * Set specific vertex data
  39142. * @param kind defines the data kind (Position, normal, etc...)
  39143. * @param data defines the vertex data to use
  39144. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39145. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39146. */
  39147. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39148. if (updatable === void 0) { updatable = false; }
  39149. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39150. this.setVerticesBuffer(buffer);
  39151. };
  39152. /**
  39153. * Removes a specific vertex data
  39154. * @param kind defines the data kind (Position, normal, etc...)
  39155. */
  39156. Geometry.prototype.removeVerticesData = function (kind) {
  39157. if (this._vertexBuffers[kind]) {
  39158. this._vertexBuffers[kind].dispose();
  39159. delete this._vertexBuffers[kind];
  39160. }
  39161. };
  39162. /**
  39163. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39164. * @param buffer defines the vertex buffer to use
  39165. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39166. */
  39167. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39168. if (totalVertices === void 0) { totalVertices = null; }
  39169. var kind = buffer.getKind();
  39170. if (this._vertexBuffers[kind]) {
  39171. this._vertexBuffers[kind].dispose();
  39172. }
  39173. this._vertexBuffers[kind] = buffer;
  39174. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39175. var data = buffer.getData();
  39176. if (totalVertices != null) {
  39177. this._totalVertices = totalVertices;
  39178. }
  39179. else {
  39180. if (data != null) {
  39181. this._totalVertices = data.length / (buffer.byteStride / 4);
  39182. }
  39183. }
  39184. this._updateExtend(data);
  39185. this._resetPointsArrayCache();
  39186. var meshes = this._meshes;
  39187. var numOfMeshes = meshes.length;
  39188. for (var index = 0; index < numOfMeshes; index++) {
  39189. var mesh = meshes[index];
  39190. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39191. mesh._createGlobalSubMesh(false);
  39192. mesh.computeWorldMatrix(true);
  39193. }
  39194. }
  39195. this.notifyUpdate(kind);
  39196. if (this._vertexArrayObjects) {
  39197. this._disposeVertexArrayObjects();
  39198. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39199. }
  39200. };
  39201. /**
  39202. * Update a specific vertex buffer
  39203. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39204. * It will do nothing if the buffer is not updatable
  39205. * @param kind defines the data kind (Position, normal, etc...)
  39206. * @param data defines the data to use
  39207. * @param offset defines the offset in the target buffer where to store the data
  39208. * @param useBytes set to true if the offset is in bytes
  39209. */
  39210. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39211. if (useBytes === void 0) { useBytes = false; }
  39212. var vertexBuffer = this.getVertexBuffer(kind);
  39213. if (!vertexBuffer) {
  39214. return;
  39215. }
  39216. vertexBuffer.updateDirectly(data, offset, useBytes);
  39217. this.notifyUpdate(kind);
  39218. };
  39219. /**
  39220. * Update a specific vertex buffer
  39221. * This function will create a new buffer if the current one is not updatable
  39222. * @param kind defines the data kind (Position, normal, etc...)
  39223. * @param data defines the data to use
  39224. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39225. */
  39226. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39227. if (updateExtends === void 0) { updateExtends = false; }
  39228. var vertexBuffer = this.getVertexBuffer(kind);
  39229. if (!vertexBuffer) {
  39230. return;
  39231. }
  39232. vertexBuffer.update(data);
  39233. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39234. this._updateBoundingInfo(updateExtends, data);
  39235. }
  39236. this.notifyUpdate(kind);
  39237. };
  39238. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39239. if (updateExtends) {
  39240. this._updateExtend(data);
  39241. }
  39242. var meshes = this._meshes;
  39243. var numOfMeshes = meshes.length;
  39244. this._resetPointsArrayCache();
  39245. for (var index = 0; index < numOfMeshes; index++) {
  39246. var mesh = meshes[index];
  39247. if (updateExtends) {
  39248. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39249. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39250. var subMesh = mesh.subMeshes[subIndex];
  39251. subMesh.refreshBoundingInfo();
  39252. }
  39253. }
  39254. }
  39255. };
  39256. /** @hidden */
  39257. Geometry.prototype._bind = function (effect, indexToBind) {
  39258. if (!effect) {
  39259. return;
  39260. }
  39261. if (indexToBind === undefined) {
  39262. indexToBind = this._indexBuffer;
  39263. }
  39264. var vbs = this.getVertexBuffers();
  39265. if (!vbs) {
  39266. return;
  39267. }
  39268. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39269. this._engine.bindBuffers(vbs, indexToBind, effect);
  39270. return;
  39271. }
  39272. // Using VAO
  39273. if (!this._vertexArrayObjects[effect.key]) {
  39274. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39275. }
  39276. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39277. };
  39278. /**
  39279. * Gets total number of vertices
  39280. * @returns the total number of vertices
  39281. */
  39282. Geometry.prototype.getTotalVertices = function () {
  39283. if (!this.isReady()) {
  39284. return 0;
  39285. }
  39286. return this._totalVertices;
  39287. };
  39288. /**
  39289. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39290. * @param kind defines the data kind (Position, normal, etc...)
  39291. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39292. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39293. * @returns a float array containing vertex data
  39294. */
  39295. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39296. var vertexBuffer = this.getVertexBuffer(kind);
  39297. if (!vertexBuffer) {
  39298. return null;
  39299. }
  39300. var data = vertexBuffer.getData();
  39301. if (!data) {
  39302. return null;
  39303. }
  39304. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39305. var count = this._totalVertices * vertexBuffer.getSize();
  39306. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39307. var copy_1 = new Array(count);
  39308. vertexBuffer.forEach(count, function (value, index) {
  39309. copy_1[index] = value;
  39310. });
  39311. return copy_1;
  39312. }
  39313. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39314. if (data instanceof Array) {
  39315. var offset = vertexBuffer.byteOffset / 4;
  39316. return BABYLON.Tools.Slice(data, offset, offset + count);
  39317. }
  39318. else if (data instanceof ArrayBuffer) {
  39319. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39320. }
  39321. else {
  39322. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39323. }
  39324. }
  39325. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39326. return BABYLON.Tools.Slice(data);
  39327. }
  39328. return data;
  39329. };
  39330. /**
  39331. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39332. * @param kind defines the data kind (Position, normal, etc...)
  39333. * @returns true if the vertex buffer with the specified kind is updatable
  39334. */
  39335. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39336. var vb = this._vertexBuffers[kind];
  39337. if (!vb) {
  39338. return false;
  39339. }
  39340. return vb.isUpdatable();
  39341. };
  39342. /**
  39343. * Gets a specific vertex buffer
  39344. * @param kind defines the data kind (Position, normal, etc...)
  39345. * @returns a {BABYLON.VertexBuffer}
  39346. */
  39347. Geometry.prototype.getVertexBuffer = function (kind) {
  39348. if (!this.isReady()) {
  39349. return null;
  39350. }
  39351. return this._vertexBuffers[kind];
  39352. };
  39353. /**
  39354. * Returns all vertex buffers
  39355. * @return an object holding all vertex buffers indexed by kind
  39356. */
  39357. Geometry.prototype.getVertexBuffers = function () {
  39358. if (!this.isReady()) {
  39359. return null;
  39360. }
  39361. return this._vertexBuffers;
  39362. };
  39363. /**
  39364. * Gets a boolean indicating if specific vertex buffer is present
  39365. * @param kind defines the data kind (Position, normal, etc...)
  39366. * @returns true if data is present
  39367. */
  39368. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39369. if (!this._vertexBuffers) {
  39370. if (this._delayInfo) {
  39371. return this._delayInfo.indexOf(kind) !== -1;
  39372. }
  39373. return false;
  39374. }
  39375. return this._vertexBuffers[kind] !== undefined;
  39376. };
  39377. /**
  39378. * Gets a list of all attached data kinds (Position, normal, etc...)
  39379. * @returns a list of string containing all kinds
  39380. */
  39381. Geometry.prototype.getVerticesDataKinds = function () {
  39382. var result = [];
  39383. var kind;
  39384. if (!this._vertexBuffers && this._delayInfo) {
  39385. for (kind in this._delayInfo) {
  39386. result.push(kind);
  39387. }
  39388. }
  39389. else {
  39390. for (kind in this._vertexBuffers) {
  39391. result.push(kind);
  39392. }
  39393. }
  39394. return result;
  39395. };
  39396. /**
  39397. * Update index buffer
  39398. * @param indices defines the indices to store in the index buffer
  39399. * @param offset defines the offset in the target buffer where to store the data
  39400. */
  39401. Geometry.prototype.updateIndices = function (indices, offset) {
  39402. if (!this._indexBuffer) {
  39403. return;
  39404. }
  39405. if (!this._indexBufferIsUpdatable) {
  39406. this.setIndices(indices, null, true);
  39407. }
  39408. else {
  39409. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39410. }
  39411. };
  39412. /**
  39413. * Creates a new index buffer
  39414. * @param indices defines the indices to store in the index buffer
  39415. * @param totalVertices defines the total number of vertices (could be null)
  39416. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39417. */
  39418. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39419. if (totalVertices === void 0) { totalVertices = null; }
  39420. if (updatable === void 0) { updatable = false; }
  39421. if (this._indexBuffer) {
  39422. this._engine._releaseBuffer(this._indexBuffer);
  39423. }
  39424. this._disposeVertexArrayObjects();
  39425. this._indices = indices;
  39426. this._indexBufferIsUpdatable = updatable;
  39427. if (this._meshes.length !== 0 && this._indices) {
  39428. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39429. }
  39430. if (totalVertices != undefined) { // including null and undefined
  39431. this._totalVertices = totalVertices;
  39432. }
  39433. var meshes = this._meshes;
  39434. var numOfMeshes = meshes.length;
  39435. for (var index = 0; index < numOfMeshes; index++) {
  39436. meshes[index]._createGlobalSubMesh(true);
  39437. }
  39438. this.notifyUpdate();
  39439. };
  39440. /**
  39441. * Return the total number of indices
  39442. * @returns the total number of indices
  39443. */
  39444. Geometry.prototype.getTotalIndices = function () {
  39445. if (!this.isReady()) {
  39446. return 0;
  39447. }
  39448. return this._indices.length;
  39449. };
  39450. /**
  39451. * Gets the index buffer array
  39452. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39453. * @returns the index buffer array
  39454. */
  39455. Geometry.prototype.getIndices = function (copyWhenShared) {
  39456. if (!this.isReady()) {
  39457. return null;
  39458. }
  39459. var orig = this._indices;
  39460. if (!copyWhenShared || this._meshes.length === 1) {
  39461. return orig;
  39462. }
  39463. else {
  39464. var len = orig.length;
  39465. var copy = [];
  39466. for (var i = 0; i < len; i++) {
  39467. copy.push(orig[i]);
  39468. }
  39469. return copy;
  39470. }
  39471. };
  39472. /**
  39473. * Gets the index buffer
  39474. * @return the index buffer
  39475. */
  39476. Geometry.prototype.getIndexBuffer = function () {
  39477. if (!this.isReady()) {
  39478. return null;
  39479. }
  39480. return this._indexBuffer;
  39481. };
  39482. /** @hidden */
  39483. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39484. if (effect === void 0) { effect = null; }
  39485. if (!effect || !this._vertexArrayObjects) {
  39486. return;
  39487. }
  39488. if (this._vertexArrayObjects[effect.key]) {
  39489. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39490. delete this._vertexArrayObjects[effect.key];
  39491. }
  39492. };
  39493. /**
  39494. * Release the associated resources for a specific mesh
  39495. * @param mesh defines the source mesh
  39496. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39497. */
  39498. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39499. var meshes = this._meshes;
  39500. var index = meshes.indexOf(mesh);
  39501. if (index === -1) {
  39502. return;
  39503. }
  39504. meshes.splice(index, 1);
  39505. mesh._geometry = null;
  39506. if (meshes.length === 0 && shouldDispose) {
  39507. this.dispose();
  39508. }
  39509. };
  39510. /**
  39511. * Apply current geometry to a given mesh
  39512. * @param mesh defines the mesh to apply geometry to
  39513. */
  39514. Geometry.prototype.applyToMesh = function (mesh) {
  39515. if (mesh._geometry === this) {
  39516. return;
  39517. }
  39518. var previousGeometry = mesh._geometry;
  39519. if (previousGeometry) {
  39520. previousGeometry.releaseForMesh(mesh);
  39521. }
  39522. var meshes = this._meshes;
  39523. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39524. mesh._geometry = this;
  39525. this._scene.pushGeometry(this);
  39526. meshes.push(mesh);
  39527. if (this.isReady()) {
  39528. this._applyToMesh(mesh);
  39529. }
  39530. else {
  39531. mesh._boundingInfo = this._boundingInfo;
  39532. }
  39533. };
  39534. Geometry.prototype._updateExtend = function (data) {
  39535. if (data === void 0) { data = null; }
  39536. if (!data) {
  39537. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39538. }
  39539. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39540. };
  39541. Geometry.prototype._applyToMesh = function (mesh) {
  39542. var numOfMeshes = this._meshes.length;
  39543. // vertexBuffers
  39544. for (var kind in this._vertexBuffers) {
  39545. if (numOfMeshes === 1) {
  39546. this._vertexBuffers[kind].create();
  39547. }
  39548. var buffer = this._vertexBuffers[kind].getBuffer();
  39549. if (buffer)
  39550. buffer.references = numOfMeshes;
  39551. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39552. if (!this._extend) {
  39553. this._updateExtend();
  39554. }
  39555. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39556. mesh._createGlobalSubMesh(false);
  39557. //bounding info was just created again, world matrix should be applied again.
  39558. mesh._updateBoundingInfo();
  39559. }
  39560. }
  39561. // indexBuffer
  39562. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39563. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39564. }
  39565. if (this._indexBuffer) {
  39566. this._indexBuffer.references = numOfMeshes;
  39567. }
  39568. };
  39569. Geometry.prototype.notifyUpdate = function (kind) {
  39570. if (this.onGeometryUpdated) {
  39571. this.onGeometryUpdated(this, kind);
  39572. }
  39573. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39574. var mesh = _a[_i];
  39575. mesh._markSubMeshesAsAttributesDirty();
  39576. }
  39577. };
  39578. /**
  39579. * Load the geometry if it was flagged as delay loaded
  39580. * @param scene defines the hosting scene
  39581. * @param onLoaded defines a callback called when the geometry is loaded
  39582. */
  39583. Geometry.prototype.load = function (scene, onLoaded) {
  39584. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39585. return;
  39586. }
  39587. if (this.isReady()) {
  39588. if (onLoaded) {
  39589. onLoaded();
  39590. }
  39591. return;
  39592. }
  39593. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39594. this._queueLoad(scene, onLoaded);
  39595. };
  39596. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39597. var _this = this;
  39598. if (!this.delayLoadingFile) {
  39599. return;
  39600. }
  39601. scene._addPendingData(this);
  39602. scene._loadFile(this.delayLoadingFile, function (data) {
  39603. if (!_this._delayLoadingFunction) {
  39604. return;
  39605. }
  39606. _this._delayLoadingFunction(JSON.parse(data), _this);
  39607. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39608. _this._delayInfo = [];
  39609. scene._removePendingData(_this);
  39610. var meshes = _this._meshes;
  39611. var numOfMeshes = meshes.length;
  39612. for (var index = 0; index < numOfMeshes; index++) {
  39613. _this._applyToMesh(meshes[index]);
  39614. }
  39615. if (onLoaded) {
  39616. onLoaded();
  39617. }
  39618. }, undefined, true);
  39619. };
  39620. /**
  39621. * Invert the geometry to move from a right handed system to a left handed one.
  39622. */
  39623. Geometry.prototype.toLeftHanded = function () {
  39624. // Flip faces
  39625. var tIndices = this.getIndices(false);
  39626. if (tIndices != null && tIndices.length > 0) {
  39627. for (var i = 0; i < tIndices.length; i += 3) {
  39628. var tTemp = tIndices[i + 0];
  39629. tIndices[i + 0] = tIndices[i + 2];
  39630. tIndices[i + 2] = tTemp;
  39631. }
  39632. this.setIndices(tIndices);
  39633. }
  39634. // Negate position.z
  39635. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39636. if (tPositions != null && tPositions.length > 0) {
  39637. for (var i = 0; i < tPositions.length; i += 3) {
  39638. tPositions[i + 2] = -tPositions[i + 2];
  39639. }
  39640. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39641. }
  39642. // Negate normal.z
  39643. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39644. if (tNormals != null && tNormals.length > 0) {
  39645. for (var i = 0; i < tNormals.length; i += 3) {
  39646. tNormals[i + 2] = -tNormals[i + 2];
  39647. }
  39648. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39649. }
  39650. };
  39651. // Cache
  39652. /** @hidden */
  39653. Geometry.prototype._resetPointsArrayCache = function () {
  39654. this._positions = null;
  39655. };
  39656. /** @hidden */
  39657. Geometry.prototype._generatePointsArray = function () {
  39658. if (this._positions)
  39659. return true;
  39660. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39661. if (!data || data.length === 0) {
  39662. return false;
  39663. }
  39664. this._positions = [];
  39665. for (var index = 0; index < data.length; index += 3) {
  39666. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39667. }
  39668. return true;
  39669. };
  39670. /**
  39671. * Gets a value indicating if the geometry is disposed
  39672. * @returns true if the geometry was disposed
  39673. */
  39674. Geometry.prototype.isDisposed = function () {
  39675. return this._isDisposed;
  39676. };
  39677. Geometry.prototype._disposeVertexArrayObjects = function () {
  39678. if (this._vertexArrayObjects) {
  39679. for (var kind in this._vertexArrayObjects) {
  39680. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39681. }
  39682. this._vertexArrayObjects = {};
  39683. }
  39684. };
  39685. /**
  39686. * Free all associated resources
  39687. */
  39688. Geometry.prototype.dispose = function () {
  39689. var meshes = this._meshes;
  39690. var numOfMeshes = meshes.length;
  39691. var index;
  39692. for (index = 0; index < numOfMeshes; index++) {
  39693. this.releaseForMesh(meshes[index]);
  39694. }
  39695. this._meshes = [];
  39696. this._disposeVertexArrayObjects();
  39697. for (var kind in this._vertexBuffers) {
  39698. this._vertexBuffers[kind].dispose();
  39699. }
  39700. this._vertexBuffers = {};
  39701. this._totalVertices = 0;
  39702. if (this._indexBuffer) {
  39703. this._engine._releaseBuffer(this._indexBuffer);
  39704. }
  39705. this._indexBuffer = null;
  39706. this._indices = [];
  39707. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39708. this.delayLoadingFile = null;
  39709. this._delayLoadingFunction = null;
  39710. this._delayInfo = [];
  39711. this._boundingInfo = null;
  39712. this._scene.removeGeometry(this);
  39713. this._isDisposed = true;
  39714. };
  39715. /**
  39716. * Clone the current geometry into a new geometry
  39717. * @param id defines the unique ID of the new geometry
  39718. * @returns a new geometry object
  39719. */
  39720. Geometry.prototype.copy = function (id) {
  39721. var vertexData = new BABYLON.VertexData();
  39722. vertexData.indices = [];
  39723. var indices = this.getIndices();
  39724. if (indices) {
  39725. for (var index = 0; index < indices.length; index++) {
  39726. vertexData.indices.push(indices[index]);
  39727. }
  39728. }
  39729. var updatable = false;
  39730. var stopChecking = false;
  39731. var kind;
  39732. for (kind in this._vertexBuffers) {
  39733. // using slice() to make a copy of the array and not just reference it
  39734. var data = this.getVerticesData(kind);
  39735. if (data instanceof Float32Array) {
  39736. vertexData.set(new Float32Array(data), kind);
  39737. }
  39738. else {
  39739. vertexData.set(data.slice(0), kind);
  39740. }
  39741. if (!stopChecking) {
  39742. var vb = this.getVertexBuffer(kind);
  39743. if (vb) {
  39744. updatable = vb.isUpdatable();
  39745. stopChecking = !updatable;
  39746. }
  39747. }
  39748. }
  39749. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39750. geometry.delayLoadState = this.delayLoadState;
  39751. geometry.delayLoadingFile = this.delayLoadingFile;
  39752. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39753. for (kind in this._delayInfo) {
  39754. geometry._delayInfo = geometry._delayInfo || [];
  39755. geometry._delayInfo.push(kind);
  39756. }
  39757. // Bounding info
  39758. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39759. return geometry;
  39760. };
  39761. /**
  39762. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39763. * @return a JSON representation of the current geometry data (without the vertices data)
  39764. */
  39765. Geometry.prototype.serialize = function () {
  39766. var serializationObject = {};
  39767. serializationObject.id = this.id;
  39768. serializationObject.updatable = this._updatable;
  39769. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39770. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39771. }
  39772. return serializationObject;
  39773. };
  39774. Geometry.prototype.toNumberArray = function (origin) {
  39775. if (Array.isArray(origin)) {
  39776. return origin;
  39777. }
  39778. else {
  39779. return Array.prototype.slice.call(origin);
  39780. }
  39781. };
  39782. /**
  39783. * Serialize all vertices data into a JSON oject
  39784. * @returns a JSON representation of the current geometry data
  39785. */
  39786. Geometry.prototype.serializeVerticeData = function () {
  39787. var serializationObject = this.serialize();
  39788. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39789. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39790. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39791. serializationObject.positions._updatable = true;
  39792. }
  39793. }
  39794. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39795. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39796. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39797. serializationObject.normals._updatable = true;
  39798. }
  39799. }
  39800. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39801. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39802. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39803. serializationObject.tangets._updatable = true;
  39804. }
  39805. }
  39806. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39807. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39808. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39809. serializationObject.uvs._updatable = true;
  39810. }
  39811. }
  39812. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39813. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39814. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39815. serializationObject.uv2s._updatable = true;
  39816. }
  39817. }
  39818. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39819. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39820. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39821. serializationObject.uv3s._updatable = true;
  39822. }
  39823. }
  39824. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39825. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39826. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39827. serializationObject.uv4s._updatable = true;
  39828. }
  39829. }
  39830. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39831. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39832. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39833. serializationObject.uv5s._updatable = true;
  39834. }
  39835. }
  39836. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39837. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39838. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39839. serializationObject.uv6s._updatable = true;
  39840. }
  39841. }
  39842. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39843. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39844. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39845. serializationObject.colors._updatable = true;
  39846. }
  39847. }
  39848. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39849. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39850. serializationObject.matricesIndices._isExpanded = true;
  39851. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39852. serializationObject.matricesIndices._updatable = true;
  39853. }
  39854. }
  39855. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39856. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39857. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39858. serializationObject.matricesWeights._updatable = true;
  39859. }
  39860. }
  39861. serializationObject.indices = this.toNumberArray(this.getIndices());
  39862. return serializationObject;
  39863. };
  39864. // Statics
  39865. /**
  39866. * Extracts a clone of a mesh geometry
  39867. * @param mesh defines the source mesh
  39868. * @param id defines the unique ID of the new geometry object
  39869. * @returns the new geometry object
  39870. */
  39871. Geometry.ExtractFromMesh = function (mesh, id) {
  39872. var geometry = mesh._geometry;
  39873. if (!geometry) {
  39874. return null;
  39875. }
  39876. return geometry.copy(id);
  39877. };
  39878. /**
  39879. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39880. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39881. * Be aware Math.random() could cause collisions, but:
  39882. * "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"
  39883. * @returns a string containing a new GUID
  39884. */
  39885. Geometry.RandomId = function () {
  39886. return BABYLON.Tools.RandomId();
  39887. };
  39888. /** @hidden */
  39889. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39890. var scene = mesh.getScene();
  39891. // Geometry
  39892. var geometryId = parsedGeometry.geometryId;
  39893. if (geometryId) {
  39894. var geometry = scene.getGeometryByID(geometryId);
  39895. if (geometry) {
  39896. geometry.applyToMesh(mesh);
  39897. }
  39898. }
  39899. else if (parsedGeometry instanceof ArrayBuffer) {
  39900. var binaryInfo = mesh._binaryInfo;
  39901. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39902. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39903. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39904. }
  39905. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39906. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39907. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39908. }
  39909. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39910. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39911. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39912. }
  39913. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39914. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39915. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39916. }
  39917. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39918. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39919. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39920. }
  39921. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39922. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39923. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39924. }
  39925. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39926. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39927. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39928. }
  39929. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39930. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39931. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39932. }
  39933. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39934. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39935. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39936. }
  39937. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39938. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39939. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39940. }
  39941. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39942. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39943. var floatIndices = [];
  39944. for (var i = 0; i < matricesIndicesData.length; i++) {
  39945. var index = matricesIndicesData[i];
  39946. floatIndices.push(index & 0x000000FF);
  39947. floatIndices.push((index & 0x0000FF00) >> 8);
  39948. floatIndices.push((index & 0x00FF0000) >> 16);
  39949. floatIndices.push(index >> 24);
  39950. }
  39951. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39952. }
  39953. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39954. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39955. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39956. }
  39957. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39958. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39959. mesh.setIndices(indicesData, null);
  39960. }
  39961. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39962. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39963. mesh.subMeshes = [];
  39964. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39965. var materialIndex = subMeshesData[(i * 5) + 0];
  39966. var verticesStart = subMeshesData[(i * 5) + 1];
  39967. var verticesCount = subMeshesData[(i * 5) + 2];
  39968. var indexStart = subMeshesData[(i * 5) + 3];
  39969. var indexCount = subMeshesData[(i * 5) + 4];
  39970. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39971. }
  39972. }
  39973. }
  39974. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39975. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39976. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39977. if (parsedGeometry.tangents) {
  39978. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39979. }
  39980. if (parsedGeometry.uvs) {
  39981. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39982. }
  39983. if (parsedGeometry.uvs2) {
  39984. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39985. }
  39986. if (parsedGeometry.uvs3) {
  39987. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39988. }
  39989. if (parsedGeometry.uvs4) {
  39990. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39991. }
  39992. if (parsedGeometry.uvs5) {
  39993. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39994. }
  39995. if (parsedGeometry.uvs6) {
  39996. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39997. }
  39998. if (parsedGeometry.colors) {
  39999. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40000. }
  40001. if (parsedGeometry.matricesIndices) {
  40002. if (!parsedGeometry.matricesIndices._isExpanded) {
  40003. var floatIndices = [];
  40004. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40005. var matricesIndex = parsedGeometry.matricesIndices[i];
  40006. floatIndices.push(matricesIndex & 0x000000FF);
  40007. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40008. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40009. floatIndices.push(matricesIndex >> 24);
  40010. }
  40011. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40012. }
  40013. else {
  40014. delete parsedGeometry.matricesIndices._isExpanded;
  40015. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40016. }
  40017. }
  40018. if (parsedGeometry.matricesIndicesExtra) {
  40019. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40020. var floatIndices = [];
  40021. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40022. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40023. floatIndices.push(matricesIndex & 0x000000FF);
  40024. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40025. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40026. floatIndices.push(matricesIndex >> 24);
  40027. }
  40028. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40029. }
  40030. else {
  40031. delete parsedGeometry.matricesIndices._isExpanded;
  40032. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40033. }
  40034. }
  40035. if (parsedGeometry.matricesWeights) {
  40036. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40037. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40038. }
  40039. if (parsedGeometry.matricesWeightsExtra) {
  40040. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40041. }
  40042. mesh.setIndices(parsedGeometry.indices, null);
  40043. }
  40044. // SubMeshes
  40045. if (parsedGeometry.subMeshes) {
  40046. mesh.subMeshes = [];
  40047. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40048. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40049. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40050. }
  40051. }
  40052. // Flat shading
  40053. if (mesh._shouldGenerateFlatShading) {
  40054. mesh.convertToFlatShadedMesh();
  40055. delete mesh._shouldGenerateFlatShading;
  40056. }
  40057. // Update
  40058. mesh.computeWorldMatrix(true);
  40059. // Octree
  40060. var sceneOctree = scene.selectionOctree;
  40061. if (sceneOctree !== undefined && sceneOctree !== null) {
  40062. sceneOctree.addMesh(mesh);
  40063. }
  40064. };
  40065. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40066. var epsilon = 1e-3;
  40067. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40068. return;
  40069. }
  40070. var noInfluenceBoneIndex = 0.0;
  40071. if (parsedGeometry.skeletonId > -1) {
  40072. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40073. if (!skeleton) {
  40074. return;
  40075. }
  40076. noInfluenceBoneIndex = skeleton.bones.length;
  40077. }
  40078. else {
  40079. return;
  40080. }
  40081. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40082. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40083. var matricesWeights = parsedGeometry.matricesWeights;
  40084. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40085. var influencers = parsedGeometry.numBoneInfluencer;
  40086. var size = matricesWeights.length;
  40087. for (var i = 0; i < size; i += 4) {
  40088. var weight = 0.0;
  40089. var firstZeroWeight = -1;
  40090. for (var j = 0; j < 4; j++) {
  40091. var w = matricesWeights[i + j];
  40092. weight += w;
  40093. if (w < epsilon && firstZeroWeight < 0) {
  40094. firstZeroWeight = j;
  40095. }
  40096. }
  40097. if (matricesWeightsExtra) {
  40098. for (var j = 0; j < 4; j++) {
  40099. var w = matricesWeightsExtra[i + j];
  40100. weight += w;
  40101. if (w < epsilon && firstZeroWeight < 0) {
  40102. firstZeroWeight = j + 4;
  40103. }
  40104. }
  40105. }
  40106. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40107. firstZeroWeight = influencers - 1;
  40108. }
  40109. if (weight > epsilon) {
  40110. var mweight = 1.0 / weight;
  40111. for (var j = 0; j < 4; j++) {
  40112. matricesWeights[i + j] *= mweight;
  40113. }
  40114. if (matricesWeightsExtra) {
  40115. for (var j = 0; j < 4; j++) {
  40116. matricesWeightsExtra[i + j] *= mweight;
  40117. }
  40118. }
  40119. }
  40120. else {
  40121. if (firstZeroWeight >= 4) {
  40122. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40123. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40124. }
  40125. else {
  40126. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40127. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40128. }
  40129. }
  40130. }
  40131. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40132. if (parsedGeometry.matricesWeightsExtra) {
  40133. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40134. }
  40135. };
  40136. /**
  40137. * Create a new geometry from persisted data (Using .babylon file format)
  40138. * @param parsedVertexData defines the persisted data
  40139. * @param scene defines the hosting scene
  40140. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40141. * @returns the new geometry object
  40142. */
  40143. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40144. if (scene.getGeometryByID(parsedVertexData.id)) {
  40145. return null; // null since geometry could be something else than a box...
  40146. }
  40147. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40148. if (BABYLON.Tags) {
  40149. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40150. }
  40151. if (parsedVertexData.delayLoadingFile) {
  40152. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40153. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40154. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40155. geometry._delayInfo = [];
  40156. if (parsedVertexData.hasUVs) {
  40157. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40158. }
  40159. if (parsedVertexData.hasUVs2) {
  40160. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40161. }
  40162. if (parsedVertexData.hasUVs3) {
  40163. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40164. }
  40165. if (parsedVertexData.hasUVs4) {
  40166. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40167. }
  40168. if (parsedVertexData.hasUVs5) {
  40169. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40170. }
  40171. if (parsedVertexData.hasUVs6) {
  40172. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40173. }
  40174. if (parsedVertexData.hasColors) {
  40175. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40176. }
  40177. if (parsedVertexData.hasMatricesIndices) {
  40178. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40179. }
  40180. if (parsedVertexData.hasMatricesWeights) {
  40181. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40182. }
  40183. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40184. }
  40185. else {
  40186. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40187. }
  40188. scene.pushGeometry(geometry, true);
  40189. return geometry;
  40190. };
  40191. return Geometry;
  40192. }());
  40193. BABYLON.Geometry = Geometry;
  40194. // Primitives
  40195. /// Abstract class
  40196. /**
  40197. * Abstract class used to provide common services for all typed geometries
  40198. * @hidden
  40199. */
  40200. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40201. __extends(_PrimitiveGeometry, _super);
  40202. /**
  40203. * Creates a new typed geometry
  40204. * @param id defines the unique ID of the geometry
  40205. * @param scene defines the hosting scene
  40206. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40207. * @param mesh defines the hosting mesh (can be null)
  40208. */
  40209. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40210. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40211. if (mesh === void 0) { mesh = null; }
  40212. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40213. _this._canBeRegenerated = _canBeRegenerated;
  40214. _this._beingRegenerated = true;
  40215. _this.regenerate();
  40216. _this._beingRegenerated = false;
  40217. return _this;
  40218. }
  40219. /**
  40220. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40221. * @returns true if the geometry can be regenerated
  40222. */
  40223. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40224. return this._canBeRegenerated;
  40225. };
  40226. /**
  40227. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40228. */
  40229. _PrimitiveGeometry.prototype.regenerate = function () {
  40230. if (!this._canBeRegenerated) {
  40231. return;
  40232. }
  40233. this._beingRegenerated = true;
  40234. this.setAllVerticesData(this._regenerateVertexData(), false);
  40235. this._beingRegenerated = false;
  40236. };
  40237. /**
  40238. * Clone the geometry
  40239. * @param id defines the unique ID of the new geometry
  40240. * @returns the new geometry
  40241. */
  40242. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40243. return _super.prototype.copy.call(this, id);
  40244. };
  40245. // overrides
  40246. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40247. if (!this._beingRegenerated) {
  40248. return;
  40249. }
  40250. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40251. };
  40252. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40253. if (!this._beingRegenerated) {
  40254. return;
  40255. }
  40256. _super.prototype.setVerticesData.call(this, kind, data, false);
  40257. };
  40258. // to override
  40259. /** @hidden */
  40260. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40261. throw new Error("Abstract method");
  40262. };
  40263. _PrimitiveGeometry.prototype.copy = function (id) {
  40264. throw new Error("Must be overriden in sub-classes.");
  40265. };
  40266. _PrimitiveGeometry.prototype.serialize = function () {
  40267. var serializationObject = _super.prototype.serialize.call(this);
  40268. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40269. return serializationObject;
  40270. };
  40271. return _PrimitiveGeometry;
  40272. }(Geometry));
  40273. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40274. /**
  40275. * Creates a ribbon geometry
  40276. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40277. */
  40278. var RibbonGeometry = /** @class */ (function (_super) {
  40279. __extends(RibbonGeometry, _super);
  40280. /**
  40281. * Creates a ribbon geometry
  40282. * @param id defines the unique ID of the geometry
  40283. * @param scene defines the hosting scene
  40284. * @param pathArray defines the array of paths to use
  40285. * @param closeArray defines if the last path and the first path must be joined
  40286. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40287. * @param offset defines the offset between points
  40288. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40289. * @param mesh defines the hosting mesh (can be null)
  40290. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40291. */
  40292. function RibbonGeometry(id, scene,
  40293. /**
  40294. * Defines the array of paths to use
  40295. */
  40296. pathArray,
  40297. /**
  40298. * Defines if the last and first points of each path in your pathArray must be joined
  40299. */
  40300. closeArray,
  40301. /**
  40302. * Defines if the last and first points of each path in your pathArray must be joined
  40303. */
  40304. closePath,
  40305. /**
  40306. * Defines the offset between points
  40307. */
  40308. offset, canBeRegenerated, mesh,
  40309. /**
  40310. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40311. */
  40312. side) {
  40313. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40314. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40315. _this.pathArray = pathArray;
  40316. _this.closeArray = closeArray;
  40317. _this.closePath = closePath;
  40318. _this.offset = offset;
  40319. _this.side = side;
  40320. return _this;
  40321. }
  40322. /** @hidden */
  40323. RibbonGeometry.prototype._regenerateVertexData = function () {
  40324. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40325. };
  40326. RibbonGeometry.prototype.copy = function (id) {
  40327. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40328. };
  40329. return RibbonGeometry;
  40330. }(_PrimitiveGeometry));
  40331. BABYLON.RibbonGeometry = RibbonGeometry;
  40332. /**
  40333. * Creates a box geometry
  40334. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40335. */
  40336. var BoxGeometry = /** @class */ (function (_super) {
  40337. __extends(BoxGeometry, _super);
  40338. /**
  40339. * Creates a box geometry
  40340. * @param id defines the unique ID of the geometry
  40341. * @param scene defines the hosting scene
  40342. * @param size defines the zise of the box (width, height and depth are the same)
  40343. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40344. * @param mesh defines the hosting mesh (can be null)
  40345. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40346. */
  40347. function BoxGeometry(id, scene,
  40348. /**
  40349. * Defines the zise of the box (width, height and depth are the same)
  40350. */
  40351. size, canBeRegenerated, mesh,
  40352. /**
  40353. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40354. */
  40355. side) {
  40356. if (mesh === void 0) { mesh = null; }
  40357. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40358. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40359. _this.size = size;
  40360. _this.side = side;
  40361. return _this;
  40362. }
  40363. BoxGeometry.prototype._regenerateVertexData = function () {
  40364. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40365. };
  40366. BoxGeometry.prototype.copy = function (id) {
  40367. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40368. };
  40369. BoxGeometry.prototype.serialize = function () {
  40370. var serializationObject = _super.prototype.serialize.call(this);
  40371. serializationObject.size = this.size;
  40372. return serializationObject;
  40373. };
  40374. BoxGeometry.Parse = function (parsedBox, scene) {
  40375. if (scene.getGeometryByID(parsedBox.id)) {
  40376. return null; // null since geometry could be something else than a box...
  40377. }
  40378. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40379. if (BABYLON.Tags) {
  40380. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40381. }
  40382. scene.pushGeometry(box, true);
  40383. return box;
  40384. };
  40385. return BoxGeometry;
  40386. }(_PrimitiveGeometry));
  40387. BABYLON.BoxGeometry = BoxGeometry;
  40388. /**
  40389. * Creates a sphere geometry
  40390. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40391. */
  40392. var SphereGeometry = /** @class */ (function (_super) {
  40393. __extends(SphereGeometry, _super);
  40394. /**
  40395. * Create a new sphere geometry
  40396. * @param id defines the unique ID of the geometry
  40397. * @param scene defines the hosting scene
  40398. * @param segments defines the number of segments to use to create the sphere
  40399. * @param diameter defines the diameter of the sphere
  40400. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40401. * @param mesh defines the hosting mesh (can be null)
  40402. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40403. */
  40404. function SphereGeometry(id, scene,
  40405. /**
  40406. * Defines the number of segments to use to create the sphere
  40407. */
  40408. segments,
  40409. /**
  40410. * Defines the diameter of the sphere
  40411. */
  40412. diameter, canBeRegenerated, mesh,
  40413. /**
  40414. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40415. */
  40416. side) {
  40417. if (mesh === void 0) { mesh = null; }
  40418. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40419. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40420. _this.segments = segments;
  40421. _this.diameter = diameter;
  40422. _this.side = side;
  40423. return _this;
  40424. }
  40425. SphereGeometry.prototype._regenerateVertexData = function () {
  40426. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40427. };
  40428. SphereGeometry.prototype.copy = function (id) {
  40429. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40430. };
  40431. SphereGeometry.prototype.serialize = function () {
  40432. var serializationObject = _super.prototype.serialize.call(this);
  40433. serializationObject.segments = this.segments;
  40434. serializationObject.diameter = this.diameter;
  40435. return serializationObject;
  40436. };
  40437. SphereGeometry.Parse = function (parsedSphere, scene) {
  40438. if (scene.getGeometryByID(parsedSphere.id)) {
  40439. return null; // null since geometry could be something else than a sphere...
  40440. }
  40441. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40442. if (BABYLON.Tags) {
  40443. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40444. }
  40445. scene.pushGeometry(sphere, true);
  40446. return sphere;
  40447. };
  40448. return SphereGeometry;
  40449. }(_PrimitiveGeometry));
  40450. BABYLON.SphereGeometry = SphereGeometry;
  40451. /**
  40452. * Creates a disc geometry
  40453. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40454. */
  40455. var DiscGeometry = /** @class */ (function (_super) {
  40456. __extends(DiscGeometry, _super);
  40457. /**
  40458. * Creates a new disc geometry
  40459. * @param id defines the unique ID of the geometry
  40460. * @param scene defines the hosting scene
  40461. * @param radius defines the radius of the disc
  40462. * @param tessellation defines the tesselation factor to apply to the disc
  40463. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40464. * @param mesh defines the hosting mesh (can be null)
  40465. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40466. */
  40467. function DiscGeometry(id, scene,
  40468. /**
  40469. * Defines the radius of the disc
  40470. */
  40471. radius,
  40472. /**
  40473. * Defines the tesselation factor to apply to the disc
  40474. */
  40475. tessellation, canBeRegenerated, mesh,
  40476. /**
  40477. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40478. */
  40479. side) {
  40480. if (mesh === void 0) { mesh = null; }
  40481. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40482. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40483. _this.radius = radius;
  40484. _this.tessellation = tessellation;
  40485. _this.side = side;
  40486. return _this;
  40487. }
  40488. DiscGeometry.prototype._regenerateVertexData = function () {
  40489. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40490. };
  40491. DiscGeometry.prototype.copy = function (id) {
  40492. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40493. };
  40494. return DiscGeometry;
  40495. }(_PrimitiveGeometry));
  40496. BABYLON.DiscGeometry = DiscGeometry;
  40497. /**
  40498. * Creates a new cylinder geometry
  40499. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40500. */
  40501. var CylinderGeometry = /** @class */ (function (_super) {
  40502. __extends(CylinderGeometry, _super);
  40503. /**
  40504. * Creates a new cylinder geometry
  40505. * @param id defines the unique ID of the geometry
  40506. * @param scene defines the hosting scene
  40507. * @param height defines the height of the cylinder
  40508. * @param diameterTop defines the diameter of the cylinder's top cap
  40509. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40510. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40511. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40512. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40513. * @param mesh defines the hosting mesh (can be null)
  40514. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40515. */
  40516. function CylinderGeometry(id, scene,
  40517. /**
  40518. * Defines the height of the cylinder
  40519. */
  40520. height,
  40521. /**
  40522. * Defines the diameter of the cylinder's top cap
  40523. */
  40524. diameterTop,
  40525. /**
  40526. * Defines the diameter of the cylinder's bottom cap
  40527. */
  40528. diameterBottom,
  40529. /**
  40530. * Defines the tessellation factor to apply to the cylinder
  40531. */
  40532. tessellation,
  40533. /**
  40534. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40535. */
  40536. subdivisions, canBeRegenerated, mesh,
  40537. /**
  40538. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40539. */
  40540. side) {
  40541. if (subdivisions === void 0) { subdivisions = 1; }
  40542. if (mesh === void 0) { mesh = null; }
  40543. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40544. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40545. _this.height = height;
  40546. _this.diameterTop = diameterTop;
  40547. _this.diameterBottom = diameterBottom;
  40548. _this.tessellation = tessellation;
  40549. _this.subdivisions = subdivisions;
  40550. _this.side = side;
  40551. return _this;
  40552. }
  40553. CylinderGeometry.prototype._regenerateVertexData = function () {
  40554. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40555. };
  40556. CylinderGeometry.prototype.copy = function (id) {
  40557. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40558. };
  40559. CylinderGeometry.prototype.serialize = function () {
  40560. var serializationObject = _super.prototype.serialize.call(this);
  40561. serializationObject.height = this.height;
  40562. serializationObject.diameterTop = this.diameterTop;
  40563. serializationObject.diameterBottom = this.diameterBottom;
  40564. serializationObject.tessellation = this.tessellation;
  40565. return serializationObject;
  40566. };
  40567. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40568. if (scene.getGeometryByID(parsedCylinder.id)) {
  40569. return null; // null since geometry could be something else than a cylinder...
  40570. }
  40571. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40572. if (BABYLON.Tags) {
  40573. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40574. }
  40575. scene.pushGeometry(cylinder, true);
  40576. return cylinder;
  40577. };
  40578. return CylinderGeometry;
  40579. }(_PrimitiveGeometry));
  40580. BABYLON.CylinderGeometry = CylinderGeometry;
  40581. /**
  40582. * Creates a new torus geometry
  40583. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40584. */
  40585. var TorusGeometry = /** @class */ (function (_super) {
  40586. __extends(TorusGeometry, _super);
  40587. /**
  40588. * Creates a new torus geometry
  40589. * @param id defines the unique ID of the geometry
  40590. * @param scene defines the hosting scene
  40591. * @param diameter defines the diameter of the torus
  40592. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40593. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40594. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40595. * @param mesh defines the hosting mesh (can be null)
  40596. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40597. */
  40598. function TorusGeometry(id, scene,
  40599. /**
  40600. * Defines the diameter of the torus
  40601. */
  40602. diameter,
  40603. /**
  40604. * Defines the thickness of the torus (ie. internal diameter)
  40605. */
  40606. thickness,
  40607. /**
  40608. * Defines the tesselation factor to apply to the torus
  40609. */
  40610. tessellation, canBeRegenerated, mesh,
  40611. /**
  40612. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40613. */
  40614. side) {
  40615. if (mesh === void 0) { mesh = null; }
  40616. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40617. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40618. _this.diameter = diameter;
  40619. _this.thickness = thickness;
  40620. _this.tessellation = tessellation;
  40621. _this.side = side;
  40622. return _this;
  40623. }
  40624. TorusGeometry.prototype._regenerateVertexData = function () {
  40625. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40626. };
  40627. TorusGeometry.prototype.copy = function (id) {
  40628. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40629. };
  40630. TorusGeometry.prototype.serialize = function () {
  40631. var serializationObject = _super.prototype.serialize.call(this);
  40632. serializationObject.diameter = this.diameter;
  40633. serializationObject.thickness = this.thickness;
  40634. serializationObject.tessellation = this.tessellation;
  40635. return serializationObject;
  40636. };
  40637. TorusGeometry.Parse = function (parsedTorus, scene) {
  40638. if (scene.getGeometryByID(parsedTorus.id)) {
  40639. return null; // null since geometry could be something else than a torus...
  40640. }
  40641. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40642. if (BABYLON.Tags) {
  40643. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40644. }
  40645. scene.pushGeometry(torus, true);
  40646. return torus;
  40647. };
  40648. return TorusGeometry;
  40649. }(_PrimitiveGeometry));
  40650. BABYLON.TorusGeometry = TorusGeometry;
  40651. /**
  40652. * Creates a new ground geometry
  40653. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40654. */
  40655. var GroundGeometry = /** @class */ (function (_super) {
  40656. __extends(GroundGeometry, _super);
  40657. /**
  40658. * Creates a new ground geometry
  40659. * @param id defines the unique ID of the geometry
  40660. * @param scene defines the hosting scene
  40661. * @param width defines the width of the ground
  40662. * @param height defines the height of the ground
  40663. * @param subdivisions defines the subdivisions to apply to the ground
  40664. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40665. * @param mesh defines the hosting mesh (can be null)
  40666. */
  40667. function GroundGeometry(id, scene,
  40668. /**
  40669. * Defines the width of the ground
  40670. */
  40671. width,
  40672. /**
  40673. * Defines the height of the ground
  40674. */
  40675. height,
  40676. /**
  40677. * Defines the subdivisions to apply to the ground
  40678. */
  40679. subdivisions, canBeRegenerated, mesh) {
  40680. if (mesh === void 0) { mesh = null; }
  40681. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40682. _this.width = width;
  40683. _this.height = height;
  40684. _this.subdivisions = subdivisions;
  40685. return _this;
  40686. }
  40687. GroundGeometry.prototype._regenerateVertexData = function () {
  40688. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40689. };
  40690. GroundGeometry.prototype.copy = function (id) {
  40691. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40692. };
  40693. GroundGeometry.prototype.serialize = function () {
  40694. var serializationObject = _super.prototype.serialize.call(this);
  40695. serializationObject.width = this.width;
  40696. serializationObject.height = this.height;
  40697. serializationObject.subdivisions = this.subdivisions;
  40698. return serializationObject;
  40699. };
  40700. GroundGeometry.Parse = function (parsedGround, scene) {
  40701. if (scene.getGeometryByID(parsedGround.id)) {
  40702. return null; // null since geometry could be something else than a ground...
  40703. }
  40704. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40705. if (BABYLON.Tags) {
  40706. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40707. }
  40708. scene.pushGeometry(ground, true);
  40709. return ground;
  40710. };
  40711. return GroundGeometry;
  40712. }(_PrimitiveGeometry));
  40713. BABYLON.GroundGeometry = GroundGeometry;
  40714. /**
  40715. * Creates a tiled ground geometry
  40716. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40717. */
  40718. var TiledGroundGeometry = /** @class */ (function (_super) {
  40719. __extends(TiledGroundGeometry, _super);
  40720. /**
  40721. * Creates a tiled ground geometry
  40722. * @param id defines the unique ID of the geometry
  40723. * @param scene defines the hosting scene
  40724. * @param xmin defines the minimum value on X axis
  40725. * @param zmin defines the minimum value on Z axis
  40726. * @param xmax defines the maximum value on X axis
  40727. * @param zmax defines the maximum value on Z axis
  40728. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40729. * @param precision defines the precision to use when computing the tiles
  40730. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40731. * @param mesh defines the hosting mesh (can be null)
  40732. */
  40733. function TiledGroundGeometry(id, scene,
  40734. /**
  40735. * Defines the minimum value on X axis
  40736. */
  40737. xmin,
  40738. /**
  40739. * Defines the minimum value on Z axis
  40740. */
  40741. zmin,
  40742. /**
  40743. * Defines the maximum value on X axis
  40744. */
  40745. xmax,
  40746. /**
  40747. * Defines the maximum value on Z axis
  40748. */
  40749. zmax,
  40750. /**
  40751. * Defines the subdivisions to apply to the ground
  40752. */
  40753. subdivisions,
  40754. /**
  40755. * Defines the precision to use when computing the tiles
  40756. */
  40757. precision, canBeRegenerated, mesh) {
  40758. if (mesh === void 0) { mesh = null; }
  40759. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40760. _this.xmin = xmin;
  40761. _this.zmin = zmin;
  40762. _this.xmax = xmax;
  40763. _this.zmax = zmax;
  40764. _this.subdivisions = subdivisions;
  40765. _this.precision = precision;
  40766. return _this;
  40767. }
  40768. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40769. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40770. };
  40771. TiledGroundGeometry.prototype.copy = function (id) {
  40772. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40773. };
  40774. return TiledGroundGeometry;
  40775. }(_PrimitiveGeometry));
  40776. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40777. /**
  40778. * Creates a plane geometry
  40779. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40780. */
  40781. var PlaneGeometry = /** @class */ (function (_super) {
  40782. __extends(PlaneGeometry, _super);
  40783. /**
  40784. * Creates a plane geometry
  40785. * @param id defines the unique ID of the geometry
  40786. * @param scene defines the hosting scene
  40787. * @param size defines the size of the plane (width === height)
  40788. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40789. * @param mesh defines the hosting mesh (can be null)
  40790. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40791. */
  40792. function PlaneGeometry(id, scene,
  40793. /**
  40794. * Defines the size of the plane (width === height)
  40795. */
  40796. size, canBeRegenerated, mesh,
  40797. /**
  40798. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40799. */
  40800. side) {
  40801. if (mesh === void 0) { mesh = null; }
  40802. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40803. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40804. _this.size = size;
  40805. _this.side = side;
  40806. return _this;
  40807. }
  40808. PlaneGeometry.prototype._regenerateVertexData = function () {
  40809. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40810. };
  40811. PlaneGeometry.prototype.copy = function (id) {
  40812. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40813. };
  40814. PlaneGeometry.prototype.serialize = function () {
  40815. var serializationObject = _super.prototype.serialize.call(this);
  40816. serializationObject.size = this.size;
  40817. return serializationObject;
  40818. };
  40819. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40820. if (scene.getGeometryByID(parsedPlane.id)) {
  40821. return null; // null since geometry could be something else than a ground...
  40822. }
  40823. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40824. if (BABYLON.Tags) {
  40825. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40826. }
  40827. scene.pushGeometry(plane, true);
  40828. return plane;
  40829. };
  40830. return PlaneGeometry;
  40831. }(_PrimitiveGeometry));
  40832. BABYLON.PlaneGeometry = PlaneGeometry;
  40833. /**
  40834. * Creates a torus knot geometry
  40835. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40836. */
  40837. var TorusKnotGeometry = /** @class */ (function (_super) {
  40838. __extends(TorusKnotGeometry, _super);
  40839. /**
  40840. * Creates a torus knot geometry
  40841. * @param id defines the unique ID of the geometry
  40842. * @param scene defines the hosting scene
  40843. * @param radius defines the radius of the torus knot
  40844. * @param tube defines the thickness of the torus knot tube
  40845. * @param radialSegments defines the number of radial segments
  40846. * @param tubularSegments defines the number of tubular segments
  40847. * @param p defines the first number of windings
  40848. * @param q defines the second number of windings
  40849. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40850. * @param mesh defines the hosting mesh (can be null)
  40851. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40852. */
  40853. function TorusKnotGeometry(id, scene,
  40854. /**
  40855. * Defines the radius of the torus knot
  40856. */
  40857. radius,
  40858. /**
  40859. * Defines the thickness of the torus knot tube
  40860. */
  40861. tube,
  40862. /**
  40863. * Defines the number of radial segments
  40864. */
  40865. radialSegments,
  40866. /**
  40867. * Defines the number of tubular segments
  40868. */
  40869. tubularSegments,
  40870. /**
  40871. * Defines the first number of windings
  40872. */
  40873. p,
  40874. /**
  40875. * Defines the second number of windings
  40876. */
  40877. q, canBeRegenerated, mesh,
  40878. /**
  40879. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40880. */
  40881. side) {
  40882. if (mesh === void 0) { mesh = null; }
  40883. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40884. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40885. _this.radius = radius;
  40886. _this.tube = tube;
  40887. _this.radialSegments = radialSegments;
  40888. _this.tubularSegments = tubularSegments;
  40889. _this.p = p;
  40890. _this.q = q;
  40891. _this.side = side;
  40892. return _this;
  40893. }
  40894. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40895. 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 });
  40896. };
  40897. TorusKnotGeometry.prototype.copy = function (id) {
  40898. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40899. };
  40900. TorusKnotGeometry.prototype.serialize = function () {
  40901. var serializationObject = _super.prototype.serialize.call(this);
  40902. serializationObject.radius = this.radius;
  40903. serializationObject.tube = this.tube;
  40904. serializationObject.radialSegments = this.radialSegments;
  40905. serializationObject.tubularSegments = this.tubularSegments;
  40906. serializationObject.p = this.p;
  40907. serializationObject.q = this.q;
  40908. return serializationObject;
  40909. };
  40910. ;
  40911. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40912. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40913. return null; // null since geometry could be something else than a ground...
  40914. }
  40915. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40916. if (BABYLON.Tags) {
  40917. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40918. }
  40919. scene.pushGeometry(torusKnot, true);
  40920. return torusKnot;
  40921. };
  40922. return TorusKnotGeometry;
  40923. }(_PrimitiveGeometry));
  40924. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40925. //}
  40926. })(BABYLON || (BABYLON = {}));
  40927. //# sourceMappingURL=babylon.geometry.js.map
  40928. var BABYLON;
  40929. (function (BABYLON) {
  40930. /**
  40931. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40932. */
  40933. var PerformanceMonitor = /** @class */ (function () {
  40934. /**
  40935. * constructor
  40936. * @param frameSampleSize The number of samples required to saturate the sliding window
  40937. */
  40938. function PerformanceMonitor(frameSampleSize) {
  40939. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40940. this._enabled = true;
  40941. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40942. }
  40943. /**
  40944. * Samples current frame
  40945. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40946. */
  40947. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40948. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40949. if (!this._enabled)
  40950. return;
  40951. if (this._lastFrameTimeMs != null) {
  40952. var dt = timeMs - this._lastFrameTimeMs;
  40953. this._rollingFrameTime.add(dt);
  40954. }
  40955. this._lastFrameTimeMs = timeMs;
  40956. };
  40957. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40958. /**
  40959. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40960. * @return Average frame time in milliseconds
  40961. */
  40962. get: function () {
  40963. return this._rollingFrameTime.average;
  40964. },
  40965. enumerable: true,
  40966. configurable: true
  40967. });
  40968. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40969. /**
  40970. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40971. * @return Frame time variance in milliseconds squared
  40972. */
  40973. get: function () {
  40974. return this._rollingFrameTime.variance;
  40975. },
  40976. enumerable: true,
  40977. configurable: true
  40978. });
  40979. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40980. /**
  40981. * Returns the frame time of the most recent frame
  40982. * @return Frame time in milliseconds
  40983. */
  40984. get: function () {
  40985. return this._rollingFrameTime.history(0);
  40986. },
  40987. enumerable: true,
  40988. configurable: true
  40989. });
  40990. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40991. /**
  40992. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40993. * @return Framerate in frames per second
  40994. */
  40995. get: function () {
  40996. return 1000.0 / this._rollingFrameTime.average;
  40997. },
  40998. enumerable: true,
  40999. configurable: true
  41000. });
  41001. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41002. /**
  41003. * Returns the average framerate in frames per second using the most recent frame time
  41004. * @return Framerate in frames per second
  41005. */
  41006. get: function () {
  41007. var history = this._rollingFrameTime.history(0);
  41008. if (history === 0) {
  41009. return 0;
  41010. }
  41011. return 1000.0 / history;
  41012. },
  41013. enumerable: true,
  41014. configurable: true
  41015. });
  41016. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41017. /**
  41018. * Returns true if enough samples have been taken to completely fill the sliding window
  41019. * @return true if saturated
  41020. */
  41021. get: function () {
  41022. return this._rollingFrameTime.isSaturated();
  41023. },
  41024. enumerable: true,
  41025. configurable: true
  41026. });
  41027. /**
  41028. * Enables contributions to the sliding window sample set
  41029. */
  41030. PerformanceMonitor.prototype.enable = function () {
  41031. this._enabled = true;
  41032. };
  41033. /**
  41034. * Disables contributions to the sliding window sample set
  41035. * Samples will not be interpolated over the disabled period
  41036. */
  41037. PerformanceMonitor.prototype.disable = function () {
  41038. this._enabled = false;
  41039. //clear last sample to avoid interpolating over the disabled period when next enabled
  41040. this._lastFrameTimeMs = null;
  41041. };
  41042. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41043. /**
  41044. * Returns true if sampling is enabled
  41045. * @return true if enabled
  41046. */
  41047. get: function () {
  41048. return this._enabled;
  41049. },
  41050. enumerable: true,
  41051. configurable: true
  41052. });
  41053. /**
  41054. * Resets performance monitor
  41055. */
  41056. PerformanceMonitor.prototype.reset = function () {
  41057. //clear last sample to avoid interpolating over the disabled period when next enabled
  41058. this._lastFrameTimeMs = null;
  41059. //wipe record
  41060. this._rollingFrameTime.reset();
  41061. };
  41062. return PerformanceMonitor;
  41063. }());
  41064. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41065. /**
  41066. * RollingAverage
  41067. *
  41068. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41069. */
  41070. var RollingAverage = /** @class */ (function () {
  41071. /**
  41072. * constructor
  41073. * @param length The number of samples required to saturate the sliding window
  41074. */
  41075. function RollingAverage(length) {
  41076. this._samples = new Array(length);
  41077. this.reset();
  41078. }
  41079. /**
  41080. * Adds a sample to the sample set
  41081. * @param v The sample value
  41082. */
  41083. RollingAverage.prototype.add = function (v) {
  41084. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41085. var delta;
  41086. //we need to check if we've already wrapped round
  41087. if (this.isSaturated()) {
  41088. //remove bottom of stack from mean
  41089. var bottomValue = this._samples[this._pos];
  41090. delta = bottomValue - this.average;
  41091. this.average -= delta / (this._sampleCount - 1);
  41092. this._m2 -= delta * (bottomValue - this.average);
  41093. }
  41094. else {
  41095. this._sampleCount++;
  41096. }
  41097. //add new value to mean
  41098. delta = v - this.average;
  41099. this.average += delta / (this._sampleCount);
  41100. this._m2 += delta * (v - this.average);
  41101. //set the new variance
  41102. this.variance = this._m2 / (this._sampleCount - 1);
  41103. this._samples[this._pos] = v;
  41104. this._pos++;
  41105. this._pos %= this._samples.length; //positive wrap around
  41106. };
  41107. /**
  41108. * Returns previously added values or null if outside of history or outside the sliding window domain
  41109. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41110. * @return Value previously recorded with add() or null if outside of range
  41111. */
  41112. RollingAverage.prototype.history = function (i) {
  41113. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41114. return 0;
  41115. }
  41116. var i0 = this._wrapPosition(this._pos - 1.0);
  41117. return this._samples[this._wrapPosition(i0 - i)];
  41118. };
  41119. /**
  41120. * Returns true if enough samples have been taken to completely fill the sliding window
  41121. * @return true if sample-set saturated
  41122. */
  41123. RollingAverage.prototype.isSaturated = function () {
  41124. return this._sampleCount >= this._samples.length;
  41125. };
  41126. /**
  41127. * Resets the rolling average (equivalent to 0 samples taken so far)
  41128. */
  41129. RollingAverage.prototype.reset = function () {
  41130. this.average = 0;
  41131. this.variance = 0;
  41132. this._sampleCount = 0;
  41133. this._pos = 0;
  41134. this._m2 = 0;
  41135. };
  41136. /**
  41137. * Wraps a value around the sample range boundaries
  41138. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41139. * @return Wrapped position in sample range
  41140. */
  41141. RollingAverage.prototype._wrapPosition = function (i) {
  41142. var max = this._samples.length;
  41143. return ((i % max) + max) % max;
  41144. };
  41145. return RollingAverage;
  41146. }());
  41147. BABYLON.RollingAverage = RollingAverage;
  41148. })(BABYLON || (BABYLON = {}));
  41149. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41150. var BABYLON;
  41151. (function (BABYLON) {
  41152. /**
  41153. * "Static Class" containing the most commonly used helper while dealing with material for
  41154. * rendering purpose.
  41155. *
  41156. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41157. *
  41158. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41159. */
  41160. var MaterialHelper = /** @class */ (function () {
  41161. function MaterialHelper() {
  41162. }
  41163. /**
  41164. * Bind the current view position to an effect.
  41165. * @param effect The effect to be bound
  41166. * @param scene The scene the eyes position is used from
  41167. */
  41168. MaterialHelper.BindEyePosition = function (effect, scene) {
  41169. if (scene._forcedViewPosition) {
  41170. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41171. return;
  41172. }
  41173. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41174. };
  41175. /**
  41176. * Helps preparing the defines values about the UVs in used in the effect.
  41177. * UVs are shared as much as we can accross chanels in the shaders.
  41178. * @param texture The texture we are preparing the UVs for
  41179. * @param defines The defines to update
  41180. * @param key The chanel key "diffuse", "specular"... used in the shader
  41181. */
  41182. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41183. defines._needUVs = true;
  41184. defines[key] = true;
  41185. if (texture.getTextureMatrix().isIdentity(true)) {
  41186. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41187. if (texture.coordinatesIndex === 0) {
  41188. defines["MAINUV1"] = true;
  41189. }
  41190. else {
  41191. defines["MAINUV2"] = true;
  41192. }
  41193. }
  41194. else {
  41195. defines[key + "DIRECTUV"] = 0;
  41196. }
  41197. };
  41198. /**
  41199. * Binds a texture matrix value to its corrsponding uniform
  41200. * @param texture The texture to bind the matrix for
  41201. * @param uniformBuffer The uniform buffer receivin the data
  41202. * @param key The chanel key "diffuse", "specular"... used in the shader
  41203. */
  41204. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41205. var matrix = texture.getTextureMatrix();
  41206. if (!matrix.isIdentity(true)) {
  41207. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41208. }
  41209. };
  41210. /**
  41211. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41212. * @param mesh defines the current mesh
  41213. * @param scene defines the current scene
  41214. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41215. * @param pointsCloud defines if point cloud rendering has to be turned on
  41216. * @param fogEnabled defines if fog has to be turned on
  41217. * @param alphaTest defines if alpha testing has to be turned on
  41218. * @param defines defines the current list of defines
  41219. */
  41220. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41221. if (defines._areMiscDirty) {
  41222. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41223. defines["POINTSIZE"] = pointsCloud;
  41224. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41225. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41226. defines["ALPHATEST"] = alphaTest;
  41227. }
  41228. };
  41229. /**
  41230. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41231. * @param scene defines the current scene
  41232. * @param engine defines the current engine
  41233. * @param defines specifies the list of active defines
  41234. * @param useInstances defines if instances have to be turned on
  41235. * @param useClipPlane defines if clip plane have to be turned on
  41236. */
  41237. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41238. if (useClipPlane === void 0) { useClipPlane = null; }
  41239. var changed = false;
  41240. if (useClipPlane == null) {
  41241. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41242. }
  41243. if (defines["CLIPPLANE"] !== useClipPlane) {
  41244. defines["CLIPPLANE"] = useClipPlane;
  41245. changed = true;
  41246. }
  41247. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41248. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41249. changed = true;
  41250. }
  41251. if (defines["INSTANCES"] !== useInstances) {
  41252. defines["INSTANCES"] = useInstances;
  41253. changed = true;
  41254. }
  41255. if (changed) {
  41256. defines.markAsUnprocessed();
  41257. }
  41258. };
  41259. /**
  41260. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41261. * @param mesh The mesh containing the geometry data we will draw
  41262. * @param defines The defines to update
  41263. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41264. * @param useBones Precise whether bones should be used or not (override mesh info)
  41265. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41266. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41267. * @returns false if defines are considered not dirty and have not been checked
  41268. */
  41269. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41270. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41271. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41272. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41273. return false;
  41274. }
  41275. defines._normals = defines._needNormals;
  41276. defines._uvs = defines._needUVs;
  41277. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41278. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41279. defines["TANGENT"] = true;
  41280. }
  41281. if (defines._needUVs) {
  41282. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41283. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41284. }
  41285. else {
  41286. defines["UV1"] = false;
  41287. defines["UV2"] = false;
  41288. }
  41289. if (useVertexColor) {
  41290. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41291. defines["VERTEXCOLOR"] = hasVertexColors;
  41292. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41293. }
  41294. if (useBones) {
  41295. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41296. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41297. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41298. }
  41299. else {
  41300. defines["NUM_BONE_INFLUENCERS"] = 0;
  41301. defines["BonesPerMesh"] = 0;
  41302. }
  41303. }
  41304. if (useMorphTargets) {
  41305. var manager = mesh.morphTargetManager;
  41306. if (manager) {
  41307. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41308. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41309. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41310. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41311. }
  41312. else {
  41313. defines["MORPHTARGETS_TANGENT"] = false;
  41314. defines["MORPHTARGETS_NORMAL"] = false;
  41315. defines["MORPHTARGETS"] = false;
  41316. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41317. }
  41318. }
  41319. return true;
  41320. };
  41321. /**
  41322. * Prepares the defines related to the light information passed in parameter
  41323. * @param scene The scene we are intending to draw
  41324. * @param mesh The mesh the effect is compiling for
  41325. * @param defines The defines to update
  41326. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41327. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41328. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41329. * @returns true if normals will be required for the rest of the effect
  41330. */
  41331. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41332. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41333. if (disableLighting === void 0) { disableLighting = false; }
  41334. if (!defines._areLightsDirty) {
  41335. return defines._needNormals;
  41336. }
  41337. var lightIndex = 0;
  41338. var needNormals = false;
  41339. var needRebuild = false;
  41340. var lightmapMode = false;
  41341. var shadowEnabled = false;
  41342. var specularEnabled = false;
  41343. if (scene.lightsEnabled && !disableLighting) {
  41344. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41345. var light = _a[_i];
  41346. needNormals = true;
  41347. if (defines["LIGHT" + lightIndex] === undefined) {
  41348. needRebuild = true;
  41349. }
  41350. defines["LIGHT" + lightIndex] = true;
  41351. defines["SPOTLIGHT" + lightIndex] = false;
  41352. defines["HEMILIGHT" + lightIndex] = false;
  41353. defines["POINTLIGHT" + lightIndex] = false;
  41354. defines["DIRLIGHT" + lightIndex] = false;
  41355. var type;
  41356. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41357. type = "SPOTLIGHT" + lightIndex;
  41358. var spotLight = light;
  41359. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41360. }
  41361. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41362. type = "HEMILIGHT" + lightIndex;
  41363. }
  41364. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41365. type = "POINTLIGHT" + lightIndex;
  41366. }
  41367. else {
  41368. type = "DIRLIGHT" + lightIndex;
  41369. }
  41370. defines[type] = true;
  41371. // Specular
  41372. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41373. specularEnabled = true;
  41374. }
  41375. // Shadows
  41376. defines["SHADOW" + lightIndex] = false;
  41377. defines["SHADOWPCF" + lightIndex] = false;
  41378. defines["SHADOWPCSS" + lightIndex] = false;
  41379. defines["SHADOWPOISSON" + lightIndex] = false;
  41380. defines["SHADOWESM" + lightIndex] = false;
  41381. defines["SHADOWCUBE" + lightIndex] = false;
  41382. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41383. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41384. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41385. var shadowGenerator = light.getShadowGenerator();
  41386. if (shadowGenerator) {
  41387. shadowEnabled = true;
  41388. shadowGenerator.prepareDefines(defines, lightIndex);
  41389. }
  41390. }
  41391. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41392. lightmapMode = true;
  41393. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41394. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41395. }
  41396. else {
  41397. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41398. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41399. }
  41400. lightIndex++;
  41401. if (lightIndex === maxSimultaneousLights)
  41402. break;
  41403. }
  41404. }
  41405. defines["SPECULARTERM"] = specularEnabled;
  41406. defines["SHADOWS"] = shadowEnabled;
  41407. // Resetting all other lights if any
  41408. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41409. if (defines["LIGHT" + index] !== undefined) {
  41410. defines["LIGHT" + index] = false;
  41411. defines["HEMILIGHT" + lightIndex] = false;
  41412. defines["POINTLIGHT" + lightIndex] = false;
  41413. defines["DIRLIGHT" + lightIndex] = false;
  41414. defines["SPOTLIGHT" + lightIndex] = false;
  41415. defines["SHADOW" + lightIndex] = false;
  41416. }
  41417. }
  41418. var caps = scene.getEngine().getCaps();
  41419. if (defines["SHADOWFLOAT"] === undefined) {
  41420. needRebuild = true;
  41421. }
  41422. defines["SHADOWFLOAT"] = shadowEnabled &&
  41423. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41424. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41425. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41426. if (needRebuild) {
  41427. defines.rebuild();
  41428. }
  41429. return needNormals;
  41430. };
  41431. /**
  41432. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41433. * that won t be acctive due to defines being turned off.
  41434. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41435. * @param samplersList The samplers list
  41436. * @param defines The defines helping in the list generation
  41437. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41438. */
  41439. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41440. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41441. var uniformsList;
  41442. var uniformBuffersList = null;
  41443. if (uniformsListOrOptions.uniformsNames) {
  41444. var options = uniformsListOrOptions;
  41445. uniformsList = options.uniformsNames;
  41446. uniformBuffersList = options.uniformBuffersNames;
  41447. samplersList = options.samplers;
  41448. defines = options.defines;
  41449. maxSimultaneousLights = options.maxSimultaneousLights;
  41450. }
  41451. else {
  41452. uniformsList = uniformsListOrOptions;
  41453. if (!samplersList) {
  41454. samplersList = [];
  41455. }
  41456. }
  41457. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41458. if (!defines["LIGHT" + lightIndex]) {
  41459. break;
  41460. }
  41461. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41462. if (uniformBuffersList) {
  41463. uniformBuffersList.push("Light" + lightIndex);
  41464. }
  41465. samplersList.push("shadowSampler" + lightIndex);
  41466. samplersList.push("depthSampler" + lightIndex);
  41467. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41468. samplersList.push("projectionLightSampler" + lightIndex);
  41469. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41470. }
  41471. }
  41472. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41473. uniformsList.push("morphTargetInfluences");
  41474. }
  41475. };
  41476. /**
  41477. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41478. * @param defines The defines to update while falling back
  41479. * @param fallbacks The authorized effect fallbacks
  41480. * @param maxSimultaneousLights The maximum number of lights allowed
  41481. * @param rank the current rank of the Effect
  41482. * @returns The newly affected rank
  41483. */
  41484. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41485. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41486. if (rank === void 0) { rank = 0; }
  41487. var lightFallbackRank = 0;
  41488. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41489. if (!defines["LIGHT" + lightIndex]) {
  41490. break;
  41491. }
  41492. if (lightIndex > 0) {
  41493. lightFallbackRank = rank + lightIndex;
  41494. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41495. }
  41496. if (!defines["SHADOWS"]) {
  41497. if (defines["SHADOW" + lightIndex]) {
  41498. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41499. }
  41500. if (defines["SHADOWPCF" + lightIndex]) {
  41501. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41502. }
  41503. if (defines["SHADOWPCSS" + lightIndex]) {
  41504. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41505. }
  41506. if (defines["SHADOWPOISSON" + lightIndex]) {
  41507. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41508. }
  41509. if (defines["SHADOWESM" + lightIndex]) {
  41510. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41511. }
  41512. }
  41513. }
  41514. return lightFallbackRank++;
  41515. };
  41516. /**
  41517. * Prepares the list of attributes required for morph targets according to the effect defines.
  41518. * @param attribs The current list of supported attribs
  41519. * @param mesh The mesh to prepare the morph targets attributes for
  41520. * @param defines The current Defines of the effect
  41521. */
  41522. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41523. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41524. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41525. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41526. var manager = mesh.morphTargetManager;
  41527. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41528. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41529. for (var index = 0; index < influencers; index++) {
  41530. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41531. if (normal) {
  41532. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41533. }
  41534. if (tangent) {
  41535. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41536. }
  41537. if (attribs.length > maxAttributesCount) {
  41538. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41539. }
  41540. }
  41541. }
  41542. };
  41543. /**
  41544. * Prepares the list of attributes required for bones according to the effect defines.
  41545. * @param attribs The current list of supported attribs
  41546. * @param mesh The mesh to prepare the bones attributes for
  41547. * @param defines The current Defines of the effect
  41548. * @param fallbacks The current efffect fallback strategy
  41549. */
  41550. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41551. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41552. fallbacks.addCPUSkinningFallback(0, mesh);
  41553. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41554. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41555. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41556. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41557. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41558. }
  41559. }
  41560. };
  41561. /**
  41562. * Prepares the list of attributes required for instances according to the effect defines.
  41563. * @param attribs The current list of supported attribs
  41564. * @param defines The current Defines of the effect
  41565. */
  41566. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41567. if (defines["INSTANCES"]) {
  41568. attribs.push("world0");
  41569. attribs.push("world1");
  41570. attribs.push("world2");
  41571. attribs.push("world3");
  41572. }
  41573. };
  41574. /**
  41575. * Binds the light shadow information to the effect for the given mesh.
  41576. * @param light The light containing the generator
  41577. * @param scene The scene the lights belongs to
  41578. * @param mesh The mesh we are binding the information to render
  41579. * @param lightIndex The light index in the effect used to render the mesh
  41580. * @param effect The effect we are binding the data to
  41581. */
  41582. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41583. if (light.shadowEnabled && mesh.receiveShadows) {
  41584. var shadowGenerator = light.getShadowGenerator();
  41585. if (shadowGenerator) {
  41586. shadowGenerator.bindShadowLight(lightIndex, effect);
  41587. }
  41588. }
  41589. };
  41590. /**
  41591. * Binds the light information to the effect.
  41592. * @param light The light containing the generator
  41593. * @param effect The effect we are binding the data to
  41594. * @param lightIndex The light index in the effect used to render
  41595. */
  41596. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41597. light.transferToEffect(effect, lightIndex + "");
  41598. };
  41599. /**
  41600. * Binds the lights information from the scene to the effect for the given mesh.
  41601. * @param scene The scene the lights belongs to
  41602. * @param mesh The mesh we are binding the information to render
  41603. * @param effect The effect we are binding the data to
  41604. * @param defines The generated defines for the effect
  41605. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41606. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41607. */
  41608. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41609. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41610. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41611. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41612. for (var i = 0; i < len; i++) {
  41613. var light = mesh._lightSources[i];
  41614. var iAsString = i.toString();
  41615. var scaledIntensity = light.getScaledIntensity();
  41616. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41617. MaterialHelper.BindLightProperties(light, effect, i);
  41618. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41619. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41620. if (defines["SPECULARTERM"]) {
  41621. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41622. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41623. }
  41624. // Shadows
  41625. if (scene.shadowsEnabled) {
  41626. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41627. }
  41628. light._uniformBuffer.update();
  41629. }
  41630. };
  41631. /**
  41632. * Binds the fog information from the scene to the effect for the given mesh.
  41633. * @param scene The scene the lights belongs to
  41634. * @param mesh The mesh we are binding the information to render
  41635. * @param effect The effect we are binding the data to
  41636. */
  41637. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41638. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41639. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41640. effect.setColor3("vFogColor", scene.fogColor);
  41641. }
  41642. };
  41643. /**
  41644. * Binds the bones information from the mesh to the effect.
  41645. * @param mesh The mesh we are binding the information to render
  41646. * @param effect The effect we are binding the data to
  41647. */
  41648. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41649. if (!effect || !mesh) {
  41650. return;
  41651. }
  41652. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41653. mesh.computeBonesUsingShaders = false;
  41654. }
  41655. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41656. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41657. if (matrices) {
  41658. effect.setMatrices("mBones", matrices);
  41659. }
  41660. }
  41661. };
  41662. /**
  41663. * Binds the morph targets information from the mesh to the effect.
  41664. * @param abstractMesh The mesh we are binding the information to render
  41665. * @param effect The effect we are binding the data to
  41666. */
  41667. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41668. var manager = abstractMesh.morphTargetManager;
  41669. if (!abstractMesh || !manager) {
  41670. return;
  41671. }
  41672. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41673. };
  41674. /**
  41675. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41676. * @param defines The generated defines used in the effect
  41677. * @param effect The effect we are binding the data to
  41678. * @param scene The scene we are willing to render with logarithmic scale for
  41679. */
  41680. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41681. if (defines["LOGARITHMICDEPTH"]) {
  41682. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41683. }
  41684. };
  41685. /**
  41686. * Binds the clip plane information from the scene to the effect.
  41687. * @param scene The scene the clip plane information are extracted from
  41688. * @param effect The effect we are binding the data to
  41689. */
  41690. MaterialHelper.BindClipPlane = function (effect, scene) {
  41691. if (scene.clipPlane) {
  41692. var clipPlane = scene.clipPlane;
  41693. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41694. }
  41695. };
  41696. return MaterialHelper;
  41697. }());
  41698. BABYLON.MaterialHelper = MaterialHelper;
  41699. })(BABYLON || (BABYLON = {}));
  41700. //# sourceMappingURL=babylon.materialHelper.js.map
  41701. var BABYLON;
  41702. (function (BABYLON) {
  41703. var PushMaterial = /** @class */ (function (_super) {
  41704. __extends(PushMaterial, _super);
  41705. function PushMaterial(name, scene) {
  41706. var _this = _super.call(this, name, scene) || this;
  41707. _this._normalMatrix = new BABYLON.Matrix();
  41708. _this.storeEffectOnSubMeshes = true;
  41709. return _this;
  41710. }
  41711. PushMaterial.prototype.getEffect = function () {
  41712. return this._activeEffect;
  41713. };
  41714. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41715. if (!mesh) {
  41716. return false;
  41717. }
  41718. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41719. return true;
  41720. }
  41721. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41722. };
  41723. /**
  41724. * Binds the given world matrix to the active effect
  41725. *
  41726. * @param world the matrix to bind
  41727. */
  41728. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41729. this._activeEffect.setMatrix("world", world);
  41730. };
  41731. /**
  41732. * Binds the given normal matrix to the active effect
  41733. *
  41734. * @param normalMatrix the matrix to bind
  41735. */
  41736. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41737. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41738. };
  41739. PushMaterial.prototype.bind = function (world, mesh) {
  41740. if (!mesh) {
  41741. return;
  41742. }
  41743. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41744. };
  41745. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41746. if (effect === void 0) { effect = null; }
  41747. _super.prototype._afterBind.call(this, mesh);
  41748. this.getScene()._cachedEffect = effect;
  41749. };
  41750. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41751. if (visibility === void 0) { visibility = 1; }
  41752. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41753. };
  41754. return PushMaterial;
  41755. }(BABYLON.Material));
  41756. BABYLON.PushMaterial = PushMaterial;
  41757. })(BABYLON || (BABYLON = {}));
  41758. //# sourceMappingURL=babylon.pushMaterial.js.map
  41759. var BABYLON;
  41760. (function (BABYLON) {
  41761. /** @hidden */
  41762. var StandardMaterialDefines = /** @class */ (function (_super) {
  41763. __extends(StandardMaterialDefines, _super);
  41764. function StandardMaterialDefines() {
  41765. var _this = _super.call(this) || this;
  41766. _this.MAINUV1 = false;
  41767. _this.MAINUV2 = false;
  41768. _this.DIFFUSE = false;
  41769. _this.DIFFUSEDIRECTUV = 0;
  41770. _this.AMBIENT = false;
  41771. _this.AMBIENTDIRECTUV = 0;
  41772. _this.OPACITY = false;
  41773. _this.OPACITYDIRECTUV = 0;
  41774. _this.OPACITYRGB = false;
  41775. _this.REFLECTION = false;
  41776. _this.EMISSIVE = false;
  41777. _this.EMISSIVEDIRECTUV = 0;
  41778. _this.SPECULAR = false;
  41779. _this.SPECULARDIRECTUV = 0;
  41780. _this.BUMP = false;
  41781. _this.BUMPDIRECTUV = 0;
  41782. _this.PARALLAX = false;
  41783. _this.PARALLAXOCCLUSION = false;
  41784. _this.SPECULAROVERALPHA = false;
  41785. _this.CLIPPLANE = false;
  41786. _this.ALPHATEST = false;
  41787. _this.DEPTHPREPASS = false;
  41788. _this.ALPHAFROMDIFFUSE = false;
  41789. _this.POINTSIZE = false;
  41790. _this.FOG = false;
  41791. _this.SPECULARTERM = false;
  41792. _this.DIFFUSEFRESNEL = false;
  41793. _this.OPACITYFRESNEL = false;
  41794. _this.REFLECTIONFRESNEL = false;
  41795. _this.REFRACTIONFRESNEL = false;
  41796. _this.EMISSIVEFRESNEL = false;
  41797. _this.FRESNEL = false;
  41798. _this.NORMAL = false;
  41799. _this.UV1 = false;
  41800. _this.UV2 = false;
  41801. _this.VERTEXCOLOR = false;
  41802. _this.VERTEXALPHA = false;
  41803. _this.NUM_BONE_INFLUENCERS = 0;
  41804. _this.BonesPerMesh = 0;
  41805. _this.INSTANCES = false;
  41806. _this.GLOSSINESS = false;
  41807. _this.ROUGHNESS = false;
  41808. _this.EMISSIVEASILLUMINATION = false;
  41809. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41810. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41811. _this.LIGHTMAP = false;
  41812. _this.LIGHTMAPDIRECTUV = 0;
  41813. _this.OBJECTSPACE_NORMALMAP = false;
  41814. _this.USELIGHTMAPASSHADOWMAP = false;
  41815. _this.REFLECTIONMAP_3D = false;
  41816. _this.REFLECTIONMAP_SPHERICAL = false;
  41817. _this.REFLECTIONMAP_PLANAR = false;
  41818. _this.REFLECTIONMAP_CUBIC = false;
  41819. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41820. _this.REFLECTIONMAP_PROJECTION = false;
  41821. _this.REFLECTIONMAP_SKYBOX = false;
  41822. _this.REFLECTIONMAP_EXPLICIT = false;
  41823. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41824. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41825. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41826. _this.INVERTCUBICMAP = false;
  41827. _this.LOGARITHMICDEPTH = false;
  41828. _this.REFRACTION = false;
  41829. _this.REFRACTIONMAP_3D = false;
  41830. _this.REFLECTIONOVERALPHA = false;
  41831. _this.TWOSIDEDLIGHTING = false;
  41832. _this.SHADOWFLOAT = false;
  41833. _this.MORPHTARGETS = false;
  41834. _this.MORPHTARGETS_NORMAL = false;
  41835. _this.MORPHTARGETS_TANGENT = false;
  41836. _this.NUM_MORPH_INFLUENCERS = 0;
  41837. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41838. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41839. _this.IMAGEPROCESSING = false;
  41840. _this.VIGNETTE = false;
  41841. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41842. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41843. _this.TONEMAPPING = false;
  41844. _this.CONTRAST = false;
  41845. _this.COLORCURVES = false;
  41846. _this.COLORGRADING = false;
  41847. _this.COLORGRADING3D = false;
  41848. _this.SAMPLER3DGREENDEPTH = false;
  41849. _this.SAMPLER3DBGRMAP = false;
  41850. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41851. /**
  41852. * If the reflection texture on this material is in linear color space
  41853. * @hidden
  41854. */
  41855. _this.IS_REFLECTION_LINEAR = false;
  41856. /**
  41857. * If the refraction texture on this material is in linear color space
  41858. * @hidden
  41859. */
  41860. _this.IS_REFRACTION_LINEAR = false;
  41861. _this.EXPOSURE = false;
  41862. _this.rebuild();
  41863. return _this;
  41864. }
  41865. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41866. var modes = [
  41867. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41868. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41869. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41870. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41871. ];
  41872. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41873. var mode = modes_1[_i];
  41874. this[mode] = (mode === modeToEnable);
  41875. }
  41876. };
  41877. return StandardMaterialDefines;
  41878. }(BABYLON.MaterialDefines));
  41879. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41880. var StandardMaterial = /** @class */ (function (_super) {
  41881. __extends(StandardMaterial, _super);
  41882. function StandardMaterial(name, scene) {
  41883. var _this = _super.call(this, name, scene) || this;
  41884. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41885. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41886. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41887. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41888. _this.specularPower = 64;
  41889. _this._useAlphaFromDiffuseTexture = false;
  41890. _this._useEmissiveAsIllumination = false;
  41891. _this._linkEmissiveWithDiffuse = false;
  41892. _this._useSpecularOverAlpha = false;
  41893. _this._useReflectionOverAlpha = false;
  41894. _this._disableLighting = false;
  41895. _this._useObjectSpaceNormalMap = false;
  41896. _this._useParallax = false;
  41897. _this._useParallaxOcclusion = false;
  41898. _this.parallaxScaleBias = 0.05;
  41899. _this._roughness = 0;
  41900. _this.indexOfRefraction = 0.98;
  41901. _this.invertRefractionY = true;
  41902. /**
  41903. * Defines the alpha limits in alpha test mode
  41904. */
  41905. _this.alphaCutOff = 0.4;
  41906. _this._useLightmapAsShadowmap = false;
  41907. _this._useReflectionFresnelFromSpecular = false;
  41908. _this._useGlossinessFromSpecularMapAlpha = false;
  41909. _this._maxSimultaneousLights = 4;
  41910. /**
  41911. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41912. */
  41913. _this._invertNormalMapX = false;
  41914. /**
  41915. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41916. */
  41917. _this._invertNormalMapY = false;
  41918. /**
  41919. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41920. */
  41921. _this._twoSidedLighting = false;
  41922. _this._renderTargets = new BABYLON.SmartArray(16);
  41923. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41924. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41925. // Setup the default processing configuration to the scene.
  41926. _this._attachImageProcessingConfiguration(null);
  41927. _this.getRenderTargetTextures = function () {
  41928. _this._renderTargets.reset();
  41929. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41930. _this._renderTargets.push(_this._reflectionTexture);
  41931. }
  41932. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41933. _this._renderTargets.push(_this._refractionTexture);
  41934. }
  41935. return _this._renderTargets;
  41936. };
  41937. return _this;
  41938. }
  41939. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41940. /**
  41941. * Gets the image processing configuration used either in this material.
  41942. */
  41943. get: function () {
  41944. return this._imageProcessingConfiguration;
  41945. },
  41946. /**
  41947. * Sets the Default image processing configuration used either in the this material.
  41948. *
  41949. * If sets to null, the scene one is in use.
  41950. */
  41951. set: function (value) {
  41952. this._attachImageProcessingConfiguration(value);
  41953. // Ensure the effect will be rebuilt.
  41954. this._markAllSubMeshesAsTexturesDirty();
  41955. },
  41956. enumerable: true,
  41957. configurable: true
  41958. });
  41959. /**
  41960. * Attaches a new image processing configuration to the Standard Material.
  41961. * @param configuration
  41962. */
  41963. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41964. var _this = this;
  41965. if (configuration === this._imageProcessingConfiguration) {
  41966. return;
  41967. }
  41968. // Detaches observer.
  41969. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41970. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41971. }
  41972. // Pick the scene configuration if needed.
  41973. if (!configuration) {
  41974. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41975. }
  41976. else {
  41977. this._imageProcessingConfiguration = configuration;
  41978. }
  41979. // Attaches observer.
  41980. if (this._imageProcessingConfiguration) {
  41981. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41982. _this._markAllSubMeshesAsImageProcessingDirty();
  41983. });
  41984. }
  41985. };
  41986. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41987. /**
  41988. * Gets wether the color curves effect is enabled.
  41989. */
  41990. get: function () {
  41991. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41992. },
  41993. /**
  41994. * Sets wether the color curves effect is enabled.
  41995. */
  41996. set: function (value) {
  41997. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41998. },
  41999. enumerable: true,
  42000. configurable: true
  42001. });
  42002. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42003. /**
  42004. * Gets wether the color grading effect is enabled.
  42005. */
  42006. get: function () {
  42007. return this.imageProcessingConfiguration.colorGradingEnabled;
  42008. },
  42009. /**
  42010. * Gets wether the color grading effect is enabled.
  42011. */
  42012. set: function (value) {
  42013. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42014. },
  42015. enumerable: true,
  42016. configurable: true
  42017. });
  42018. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42019. /**
  42020. * Gets wether tonemapping is enabled or not.
  42021. */
  42022. get: function () {
  42023. return this._imageProcessingConfiguration.toneMappingEnabled;
  42024. },
  42025. /**
  42026. * Sets wether tonemapping is enabled or not
  42027. */
  42028. set: function (value) {
  42029. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42030. },
  42031. enumerable: true,
  42032. configurable: true
  42033. });
  42034. ;
  42035. ;
  42036. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42037. /**
  42038. * The camera exposure used on this material.
  42039. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42040. * This corresponds to a photographic exposure.
  42041. */
  42042. get: function () {
  42043. return this._imageProcessingConfiguration.exposure;
  42044. },
  42045. /**
  42046. * The camera exposure used on this material.
  42047. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42048. * This corresponds to a photographic exposure.
  42049. */
  42050. set: function (value) {
  42051. this._imageProcessingConfiguration.exposure = value;
  42052. },
  42053. enumerable: true,
  42054. configurable: true
  42055. });
  42056. ;
  42057. ;
  42058. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42059. /**
  42060. * Gets The camera contrast used on this material.
  42061. */
  42062. get: function () {
  42063. return this._imageProcessingConfiguration.contrast;
  42064. },
  42065. /**
  42066. * Sets The camera contrast used on this material.
  42067. */
  42068. set: function (value) {
  42069. this._imageProcessingConfiguration.contrast = value;
  42070. },
  42071. enumerable: true,
  42072. configurable: true
  42073. });
  42074. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42075. /**
  42076. * Gets the Color Grading 2D Lookup Texture.
  42077. */
  42078. get: function () {
  42079. return this._imageProcessingConfiguration.colorGradingTexture;
  42080. },
  42081. /**
  42082. * Sets the Color Grading 2D Lookup Texture.
  42083. */
  42084. set: function (value) {
  42085. this._imageProcessingConfiguration.colorGradingTexture = value;
  42086. },
  42087. enumerable: true,
  42088. configurable: true
  42089. });
  42090. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42091. /**
  42092. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42093. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42094. * 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;
  42095. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42096. */
  42097. get: function () {
  42098. return this._imageProcessingConfiguration.colorCurves;
  42099. },
  42100. /**
  42101. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42102. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42103. * 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;
  42104. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42105. */
  42106. set: function (value) {
  42107. this._imageProcessingConfiguration.colorCurves = value;
  42108. },
  42109. enumerable: true,
  42110. configurable: true
  42111. });
  42112. StandardMaterial.prototype.getClassName = function () {
  42113. return "StandardMaterial";
  42114. };
  42115. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42116. get: function () {
  42117. return this._useLogarithmicDepth;
  42118. },
  42119. set: function (value) {
  42120. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42121. this._markAllSubMeshesAsMiscDirty();
  42122. },
  42123. enumerable: true,
  42124. configurable: true
  42125. });
  42126. StandardMaterial.prototype.needAlphaBlending = function () {
  42127. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42128. };
  42129. StandardMaterial.prototype.needAlphaTesting = function () {
  42130. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42131. };
  42132. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42133. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42134. };
  42135. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42136. return this._diffuseTexture;
  42137. };
  42138. /**
  42139. * Child classes can use it to update shaders
  42140. */
  42141. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42142. if (useInstances === void 0) { useInstances = false; }
  42143. if (subMesh.effect && this.isFrozen) {
  42144. if (this._wasPreviouslyReady && subMesh.effect) {
  42145. return true;
  42146. }
  42147. }
  42148. if (!subMesh._materialDefines) {
  42149. subMesh._materialDefines = new StandardMaterialDefines();
  42150. }
  42151. var scene = this.getScene();
  42152. var defines = subMesh._materialDefines;
  42153. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42154. if (defines._renderId === scene.getRenderId()) {
  42155. return true;
  42156. }
  42157. }
  42158. var engine = scene.getEngine();
  42159. // Lights
  42160. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42161. // Textures
  42162. if (defines._areTexturesDirty) {
  42163. defines._needUVs = false;
  42164. defines.MAINUV1 = false;
  42165. defines.MAINUV2 = false;
  42166. if (scene.texturesEnabled) {
  42167. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42168. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42169. return false;
  42170. }
  42171. else {
  42172. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42173. }
  42174. }
  42175. else {
  42176. defines.DIFFUSE = false;
  42177. }
  42178. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42179. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42180. return false;
  42181. }
  42182. else {
  42183. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42184. }
  42185. }
  42186. else {
  42187. defines.AMBIENT = false;
  42188. }
  42189. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42190. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42191. return false;
  42192. }
  42193. else {
  42194. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42195. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42196. }
  42197. }
  42198. else {
  42199. defines.OPACITY = false;
  42200. }
  42201. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42202. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42203. return false;
  42204. }
  42205. else {
  42206. defines._needNormals = true;
  42207. defines.REFLECTION = true;
  42208. defines.ROUGHNESS = (this._roughness > 0);
  42209. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42210. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42211. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42212. switch (this._reflectionTexture.coordinatesMode) {
  42213. case BABYLON.Texture.EXPLICIT_MODE:
  42214. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42215. break;
  42216. case BABYLON.Texture.PLANAR_MODE:
  42217. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42218. break;
  42219. case BABYLON.Texture.PROJECTION_MODE:
  42220. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42221. break;
  42222. case BABYLON.Texture.SKYBOX_MODE:
  42223. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42224. break;
  42225. case BABYLON.Texture.SPHERICAL_MODE:
  42226. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42227. break;
  42228. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42229. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42230. break;
  42231. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42232. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42233. break;
  42234. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42235. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42236. break;
  42237. case BABYLON.Texture.CUBIC_MODE:
  42238. case BABYLON.Texture.INVCUBIC_MODE:
  42239. default:
  42240. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42241. break;
  42242. }
  42243. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42244. }
  42245. }
  42246. else {
  42247. defines.REFLECTION = false;
  42248. }
  42249. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42250. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42251. return false;
  42252. }
  42253. else {
  42254. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42255. }
  42256. }
  42257. else {
  42258. defines.EMISSIVE = false;
  42259. }
  42260. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42261. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42262. return false;
  42263. }
  42264. else {
  42265. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42266. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42267. }
  42268. }
  42269. else {
  42270. defines.LIGHTMAP = false;
  42271. }
  42272. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42273. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42274. return false;
  42275. }
  42276. else {
  42277. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42278. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42279. }
  42280. }
  42281. else {
  42282. defines.SPECULAR = false;
  42283. }
  42284. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42285. // Bump texure can not be not blocking.
  42286. if (!this._bumpTexture.isReady()) {
  42287. return false;
  42288. }
  42289. else {
  42290. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42291. defines.PARALLAX = this._useParallax;
  42292. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42293. }
  42294. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42295. }
  42296. else {
  42297. defines.BUMP = false;
  42298. }
  42299. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42300. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42301. return false;
  42302. }
  42303. else {
  42304. defines._needUVs = true;
  42305. defines.REFRACTION = true;
  42306. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42307. }
  42308. }
  42309. else {
  42310. defines.REFRACTION = false;
  42311. }
  42312. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42313. }
  42314. else {
  42315. defines.DIFFUSE = false;
  42316. defines.AMBIENT = false;
  42317. defines.OPACITY = false;
  42318. defines.REFLECTION = false;
  42319. defines.EMISSIVE = false;
  42320. defines.LIGHTMAP = false;
  42321. defines.BUMP = false;
  42322. defines.REFRACTION = false;
  42323. }
  42324. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42325. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42326. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42327. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42328. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42329. }
  42330. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42331. if (!this._imageProcessingConfiguration.isReady()) {
  42332. return false;
  42333. }
  42334. this._imageProcessingConfiguration.prepareDefines(defines);
  42335. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42336. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42337. }
  42338. if (defines._areFresnelDirty) {
  42339. if (StandardMaterial.FresnelEnabled) {
  42340. // Fresnel
  42341. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42342. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42343. this._reflectionFresnelParameters) {
  42344. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42345. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42346. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42347. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42348. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42349. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42350. defines._needNormals = true;
  42351. defines.FRESNEL = true;
  42352. }
  42353. }
  42354. else {
  42355. defines.FRESNEL = false;
  42356. }
  42357. }
  42358. // Misc.
  42359. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42360. // Attribs
  42361. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42362. // Values that need to be evaluated on every frame
  42363. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42364. // Get correct effect
  42365. if (defines.isDirty) {
  42366. defines.markAsProcessed();
  42367. scene.resetCachedMaterial();
  42368. // Fallbacks
  42369. var fallbacks = new BABYLON.EffectFallbacks();
  42370. if (defines.REFLECTION) {
  42371. fallbacks.addFallback(0, "REFLECTION");
  42372. }
  42373. if (defines.SPECULAR) {
  42374. fallbacks.addFallback(0, "SPECULAR");
  42375. }
  42376. if (defines.BUMP) {
  42377. fallbacks.addFallback(0, "BUMP");
  42378. }
  42379. if (defines.PARALLAX) {
  42380. fallbacks.addFallback(1, "PARALLAX");
  42381. }
  42382. if (defines.PARALLAXOCCLUSION) {
  42383. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42384. }
  42385. if (defines.SPECULAROVERALPHA) {
  42386. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42387. }
  42388. if (defines.FOG) {
  42389. fallbacks.addFallback(1, "FOG");
  42390. }
  42391. if (defines.POINTSIZE) {
  42392. fallbacks.addFallback(0, "POINTSIZE");
  42393. }
  42394. if (defines.LOGARITHMICDEPTH) {
  42395. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42396. }
  42397. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42398. if (defines.SPECULARTERM) {
  42399. fallbacks.addFallback(0, "SPECULARTERM");
  42400. }
  42401. if (defines.DIFFUSEFRESNEL) {
  42402. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42403. }
  42404. if (defines.OPACITYFRESNEL) {
  42405. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42406. }
  42407. if (defines.REFLECTIONFRESNEL) {
  42408. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42409. }
  42410. if (defines.EMISSIVEFRESNEL) {
  42411. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42412. }
  42413. if (defines.FRESNEL) {
  42414. fallbacks.addFallback(4, "FRESNEL");
  42415. }
  42416. //Attributes
  42417. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42418. if (defines.NORMAL) {
  42419. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42420. }
  42421. if (defines.UV1) {
  42422. attribs.push(BABYLON.VertexBuffer.UVKind);
  42423. }
  42424. if (defines.UV2) {
  42425. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42426. }
  42427. if (defines.VERTEXCOLOR) {
  42428. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42429. }
  42430. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42431. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42432. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42433. var shaderName = "default";
  42434. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42435. "vFogInfos", "vFogColor", "pointSize",
  42436. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42437. "mBones",
  42438. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42439. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42440. "vReflectionPosition", "vReflectionSize",
  42441. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42442. ];
  42443. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42444. var uniformBuffers = ["Material", "Scene"];
  42445. if (BABYLON.ImageProcessingConfiguration) {
  42446. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42447. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42448. }
  42449. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42450. uniformsNames: uniforms,
  42451. uniformBuffersNames: uniformBuffers,
  42452. samplers: samplers,
  42453. defines: defines,
  42454. maxSimultaneousLights: this._maxSimultaneousLights
  42455. });
  42456. if (this.customShaderNameResolve) {
  42457. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42458. }
  42459. var join = defines.toString();
  42460. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42461. attributes: attribs,
  42462. uniformsNames: uniforms,
  42463. uniformBuffersNames: uniformBuffers,
  42464. samplers: samplers,
  42465. defines: join,
  42466. fallbacks: fallbacks,
  42467. onCompiled: this.onCompiled,
  42468. onError: this.onError,
  42469. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42470. }, engine), defines);
  42471. this.buildUniformLayout();
  42472. }
  42473. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42474. return false;
  42475. }
  42476. defines._renderId = scene.getRenderId();
  42477. this._wasPreviouslyReady = true;
  42478. return true;
  42479. };
  42480. StandardMaterial.prototype.buildUniformLayout = function () {
  42481. // Order is important !
  42482. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42483. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42484. this._uniformBuffer.addUniform("opacityParts", 4);
  42485. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42486. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42487. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42488. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42489. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42490. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42491. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42492. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42493. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42494. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42495. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42496. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42497. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42498. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42499. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42500. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42501. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42502. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42503. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42504. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42505. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42506. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42507. this._uniformBuffer.addUniform("specularMatrix", 16);
  42508. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42509. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42510. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42511. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42512. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42513. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42514. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42515. this._uniformBuffer.addUniform("pointSize", 1);
  42516. this._uniformBuffer.create();
  42517. };
  42518. StandardMaterial.prototype.unbind = function () {
  42519. if (this._activeEffect) {
  42520. var needFlag = false;
  42521. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42522. this._activeEffect.setTexture("reflection2DSampler", null);
  42523. needFlag = true;
  42524. }
  42525. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42526. this._activeEffect.setTexture("refraction2DSampler", null);
  42527. needFlag = true;
  42528. }
  42529. if (needFlag) {
  42530. this._markAllSubMeshesAsTexturesDirty();
  42531. }
  42532. }
  42533. _super.prototype.unbind.call(this);
  42534. };
  42535. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42536. var scene = this.getScene();
  42537. var defines = subMesh._materialDefines;
  42538. if (!defines) {
  42539. return;
  42540. }
  42541. var effect = subMesh.effect;
  42542. if (!effect) {
  42543. return;
  42544. }
  42545. this._activeEffect = effect;
  42546. // Matrices
  42547. this.bindOnlyWorldMatrix(world);
  42548. // Normal Matrix
  42549. if (defines.OBJECTSPACE_NORMALMAP) {
  42550. world.toNormalMatrix(this._normalMatrix);
  42551. this.bindOnlyNormalMatrix(this._normalMatrix);
  42552. }
  42553. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42554. // Bones
  42555. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42556. if (mustRebind) {
  42557. this._uniformBuffer.bindToEffect(effect, "Material");
  42558. this.bindViewProjection(effect);
  42559. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42560. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42561. // Fresnel
  42562. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42563. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42564. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42565. }
  42566. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42567. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42568. }
  42569. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42570. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42571. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42572. }
  42573. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42574. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42575. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42576. }
  42577. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42578. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42579. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42580. }
  42581. }
  42582. // Textures
  42583. if (scene.texturesEnabled) {
  42584. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42585. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42586. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42587. if (this._diffuseTexture.hasAlpha) {
  42588. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42589. }
  42590. }
  42591. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42592. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42593. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42594. }
  42595. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42596. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42597. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42598. }
  42599. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42600. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42601. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42602. if (this._reflectionTexture.boundingBoxSize) {
  42603. var cubeTexture = this._reflectionTexture;
  42604. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42605. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42606. }
  42607. }
  42608. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42609. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42610. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42611. }
  42612. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42613. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42614. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42615. }
  42616. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42617. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42618. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42619. }
  42620. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42621. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42622. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42623. if (scene._mirroredCameraPosition) {
  42624. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42625. }
  42626. else {
  42627. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42628. }
  42629. }
  42630. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42631. var depth = 1.0;
  42632. if (!this._refractionTexture.isCube) {
  42633. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42634. if (this._refractionTexture.depth) {
  42635. depth = this._refractionTexture.depth;
  42636. }
  42637. }
  42638. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42639. }
  42640. }
  42641. // Point size
  42642. if (this.pointsCloud) {
  42643. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42644. }
  42645. if (defines.SPECULARTERM) {
  42646. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42647. }
  42648. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42649. // Diffuse
  42650. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42651. }
  42652. // Textures
  42653. if (scene.texturesEnabled) {
  42654. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42655. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42656. }
  42657. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42658. effect.setTexture("ambientSampler", this._ambientTexture);
  42659. }
  42660. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42661. effect.setTexture("opacitySampler", this._opacityTexture);
  42662. }
  42663. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42664. if (this._reflectionTexture.isCube) {
  42665. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42666. }
  42667. else {
  42668. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42669. }
  42670. }
  42671. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42672. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42673. }
  42674. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42675. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42676. }
  42677. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42678. effect.setTexture("specularSampler", this._specularTexture);
  42679. }
  42680. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42681. effect.setTexture("bumpSampler", this._bumpTexture);
  42682. }
  42683. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42684. var depth = 1.0;
  42685. if (this._refractionTexture.isCube) {
  42686. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42687. }
  42688. else {
  42689. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42690. }
  42691. }
  42692. }
  42693. // Clip plane
  42694. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42695. // Colors
  42696. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42697. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42698. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42699. }
  42700. if (mustRebind || !this.isFrozen) {
  42701. // Lights
  42702. if (scene.lightsEnabled && !this._disableLighting) {
  42703. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42704. }
  42705. // View
  42706. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42707. this.bindView(effect);
  42708. }
  42709. // Fog
  42710. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42711. // Morph targets
  42712. if (defines.NUM_MORPH_INFLUENCERS) {
  42713. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42714. }
  42715. // Log. depth
  42716. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42717. // image processing
  42718. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42719. this._imageProcessingConfiguration.bind(this._activeEffect);
  42720. }
  42721. }
  42722. this._uniformBuffer.update();
  42723. this._afterBind(mesh, this._activeEffect);
  42724. };
  42725. StandardMaterial.prototype.getAnimatables = function () {
  42726. var results = [];
  42727. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42728. results.push(this._diffuseTexture);
  42729. }
  42730. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42731. results.push(this._ambientTexture);
  42732. }
  42733. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42734. results.push(this._opacityTexture);
  42735. }
  42736. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42737. results.push(this._reflectionTexture);
  42738. }
  42739. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42740. results.push(this._emissiveTexture);
  42741. }
  42742. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42743. results.push(this._specularTexture);
  42744. }
  42745. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42746. results.push(this._bumpTexture);
  42747. }
  42748. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42749. results.push(this._lightmapTexture);
  42750. }
  42751. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42752. results.push(this._refractionTexture);
  42753. }
  42754. return results;
  42755. };
  42756. StandardMaterial.prototype.getActiveTextures = function () {
  42757. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42758. if (this._diffuseTexture) {
  42759. activeTextures.push(this._diffuseTexture);
  42760. }
  42761. if (this._ambientTexture) {
  42762. activeTextures.push(this._ambientTexture);
  42763. }
  42764. if (this._opacityTexture) {
  42765. activeTextures.push(this._opacityTexture);
  42766. }
  42767. if (this._reflectionTexture) {
  42768. activeTextures.push(this._reflectionTexture);
  42769. }
  42770. if (this._emissiveTexture) {
  42771. activeTextures.push(this._emissiveTexture);
  42772. }
  42773. if (this._specularTexture) {
  42774. activeTextures.push(this._specularTexture);
  42775. }
  42776. if (this._bumpTexture) {
  42777. activeTextures.push(this._bumpTexture);
  42778. }
  42779. if (this._lightmapTexture) {
  42780. activeTextures.push(this._lightmapTexture);
  42781. }
  42782. if (this._refractionTexture) {
  42783. activeTextures.push(this._refractionTexture);
  42784. }
  42785. return activeTextures;
  42786. };
  42787. StandardMaterial.prototype.hasTexture = function (texture) {
  42788. if (_super.prototype.hasTexture.call(this, texture)) {
  42789. return true;
  42790. }
  42791. if (this._diffuseTexture === texture) {
  42792. return true;
  42793. }
  42794. if (this._ambientTexture === texture) {
  42795. return true;
  42796. }
  42797. if (this._opacityTexture === texture) {
  42798. return true;
  42799. }
  42800. if (this._reflectionTexture === texture) {
  42801. return true;
  42802. }
  42803. if (this._emissiveTexture === texture) {
  42804. return true;
  42805. }
  42806. if (this._specularTexture === texture) {
  42807. return true;
  42808. }
  42809. if (this._bumpTexture === texture) {
  42810. return true;
  42811. }
  42812. if (this._lightmapTexture === texture) {
  42813. return true;
  42814. }
  42815. if (this._refractionTexture === texture) {
  42816. return true;
  42817. }
  42818. return false;
  42819. };
  42820. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42821. if (forceDisposeTextures) {
  42822. if (this._diffuseTexture) {
  42823. this._diffuseTexture.dispose();
  42824. }
  42825. if (this._ambientTexture) {
  42826. this._ambientTexture.dispose();
  42827. }
  42828. if (this._opacityTexture) {
  42829. this._opacityTexture.dispose();
  42830. }
  42831. if (this._reflectionTexture) {
  42832. this._reflectionTexture.dispose();
  42833. }
  42834. if (this._emissiveTexture) {
  42835. this._emissiveTexture.dispose();
  42836. }
  42837. if (this._specularTexture) {
  42838. this._specularTexture.dispose();
  42839. }
  42840. if (this._bumpTexture) {
  42841. this._bumpTexture.dispose();
  42842. }
  42843. if (this._lightmapTexture) {
  42844. this._lightmapTexture.dispose();
  42845. }
  42846. if (this._refractionTexture) {
  42847. this._refractionTexture.dispose();
  42848. }
  42849. }
  42850. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42851. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42852. }
  42853. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42854. };
  42855. StandardMaterial.prototype.clone = function (name) {
  42856. var _this = this;
  42857. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42858. result.name = name;
  42859. result.id = name;
  42860. return result;
  42861. };
  42862. StandardMaterial.prototype.serialize = function () {
  42863. return BABYLON.SerializationHelper.Serialize(this);
  42864. };
  42865. // Statics
  42866. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42867. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42868. };
  42869. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42870. get: function () {
  42871. return StandardMaterial._DiffuseTextureEnabled;
  42872. },
  42873. set: function (value) {
  42874. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42875. return;
  42876. }
  42877. StandardMaterial._DiffuseTextureEnabled = value;
  42878. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42879. },
  42880. enumerable: true,
  42881. configurable: true
  42882. });
  42883. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42884. get: function () {
  42885. return StandardMaterial._AmbientTextureEnabled;
  42886. },
  42887. set: function (value) {
  42888. if (StandardMaterial._AmbientTextureEnabled === value) {
  42889. return;
  42890. }
  42891. StandardMaterial._AmbientTextureEnabled = value;
  42892. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42893. },
  42894. enumerable: true,
  42895. configurable: true
  42896. });
  42897. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42898. get: function () {
  42899. return StandardMaterial._OpacityTextureEnabled;
  42900. },
  42901. set: function (value) {
  42902. if (StandardMaterial._OpacityTextureEnabled === value) {
  42903. return;
  42904. }
  42905. StandardMaterial._OpacityTextureEnabled = value;
  42906. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42907. },
  42908. enumerable: true,
  42909. configurable: true
  42910. });
  42911. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42912. get: function () {
  42913. return StandardMaterial._ReflectionTextureEnabled;
  42914. },
  42915. set: function (value) {
  42916. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42917. return;
  42918. }
  42919. StandardMaterial._ReflectionTextureEnabled = value;
  42920. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42921. },
  42922. enumerable: true,
  42923. configurable: true
  42924. });
  42925. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42926. get: function () {
  42927. return StandardMaterial._EmissiveTextureEnabled;
  42928. },
  42929. set: function (value) {
  42930. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42931. return;
  42932. }
  42933. StandardMaterial._EmissiveTextureEnabled = value;
  42934. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42935. },
  42936. enumerable: true,
  42937. configurable: true
  42938. });
  42939. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42940. get: function () {
  42941. return StandardMaterial._SpecularTextureEnabled;
  42942. },
  42943. set: function (value) {
  42944. if (StandardMaterial._SpecularTextureEnabled === value) {
  42945. return;
  42946. }
  42947. StandardMaterial._SpecularTextureEnabled = value;
  42948. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42949. },
  42950. enumerable: true,
  42951. configurable: true
  42952. });
  42953. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42954. get: function () {
  42955. return StandardMaterial._BumpTextureEnabled;
  42956. },
  42957. set: function (value) {
  42958. if (StandardMaterial._BumpTextureEnabled === value) {
  42959. return;
  42960. }
  42961. StandardMaterial._BumpTextureEnabled = value;
  42962. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42963. },
  42964. enumerable: true,
  42965. configurable: true
  42966. });
  42967. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42968. get: function () {
  42969. return StandardMaterial._LightmapTextureEnabled;
  42970. },
  42971. set: function (value) {
  42972. if (StandardMaterial._LightmapTextureEnabled === value) {
  42973. return;
  42974. }
  42975. StandardMaterial._LightmapTextureEnabled = value;
  42976. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42977. },
  42978. enumerable: true,
  42979. configurable: true
  42980. });
  42981. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42982. get: function () {
  42983. return StandardMaterial._RefractionTextureEnabled;
  42984. },
  42985. set: function (value) {
  42986. if (StandardMaterial._RefractionTextureEnabled === value) {
  42987. return;
  42988. }
  42989. StandardMaterial._RefractionTextureEnabled = value;
  42990. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42991. },
  42992. enumerable: true,
  42993. configurable: true
  42994. });
  42995. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42996. get: function () {
  42997. return StandardMaterial._ColorGradingTextureEnabled;
  42998. },
  42999. set: function (value) {
  43000. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43001. return;
  43002. }
  43003. StandardMaterial._ColorGradingTextureEnabled = value;
  43004. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43005. },
  43006. enumerable: true,
  43007. configurable: true
  43008. });
  43009. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43010. get: function () {
  43011. return StandardMaterial._FresnelEnabled;
  43012. },
  43013. set: function (value) {
  43014. if (StandardMaterial._FresnelEnabled === value) {
  43015. return;
  43016. }
  43017. StandardMaterial._FresnelEnabled = value;
  43018. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43019. },
  43020. enumerable: true,
  43021. configurable: true
  43022. });
  43023. // Flags used to enable or disable a type of texture for all Standard Materials
  43024. StandardMaterial._DiffuseTextureEnabled = true;
  43025. StandardMaterial._AmbientTextureEnabled = true;
  43026. StandardMaterial._OpacityTextureEnabled = true;
  43027. StandardMaterial._ReflectionTextureEnabled = true;
  43028. StandardMaterial._EmissiveTextureEnabled = true;
  43029. StandardMaterial._SpecularTextureEnabled = true;
  43030. StandardMaterial._BumpTextureEnabled = true;
  43031. StandardMaterial._LightmapTextureEnabled = true;
  43032. StandardMaterial._RefractionTextureEnabled = true;
  43033. StandardMaterial._ColorGradingTextureEnabled = true;
  43034. StandardMaterial._FresnelEnabled = true;
  43035. __decorate([
  43036. BABYLON.serializeAsTexture("diffuseTexture")
  43037. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43038. __decorate([
  43039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43040. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43041. __decorate([
  43042. BABYLON.serializeAsTexture("ambientTexture")
  43043. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43044. __decorate([
  43045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43046. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43047. __decorate([
  43048. BABYLON.serializeAsTexture("opacityTexture")
  43049. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43050. __decorate([
  43051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43052. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43053. __decorate([
  43054. BABYLON.serializeAsTexture("reflectionTexture")
  43055. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43056. __decorate([
  43057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43058. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43059. __decorate([
  43060. BABYLON.serializeAsTexture("emissiveTexture")
  43061. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43062. __decorate([
  43063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43064. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43065. __decorate([
  43066. BABYLON.serializeAsTexture("specularTexture")
  43067. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43068. __decorate([
  43069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43070. ], StandardMaterial.prototype, "specularTexture", void 0);
  43071. __decorate([
  43072. BABYLON.serializeAsTexture("bumpTexture")
  43073. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43074. __decorate([
  43075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43076. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43077. __decorate([
  43078. BABYLON.serializeAsTexture("lightmapTexture")
  43079. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43080. __decorate([
  43081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43082. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43083. __decorate([
  43084. BABYLON.serializeAsTexture("refractionTexture")
  43085. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43086. __decorate([
  43087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43088. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43089. __decorate([
  43090. BABYLON.serializeAsColor3("ambient")
  43091. ], StandardMaterial.prototype, "ambientColor", void 0);
  43092. __decorate([
  43093. BABYLON.serializeAsColor3("diffuse")
  43094. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43095. __decorate([
  43096. BABYLON.serializeAsColor3("specular")
  43097. ], StandardMaterial.prototype, "specularColor", void 0);
  43098. __decorate([
  43099. BABYLON.serializeAsColor3("emissive")
  43100. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43101. __decorate([
  43102. BABYLON.serialize()
  43103. ], StandardMaterial.prototype, "specularPower", void 0);
  43104. __decorate([
  43105. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43106. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43107. __decorate([
  43108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43109. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43110. __decorate([
  43111. BABYLON.serialize("useEmissiveAsIllumination")
  43112. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43113. __decorate([
  43114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43115. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43116. __decorate([
  43117. BABYLON.serialize("linkEmissiveWithDiffuse")
  43118. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43119. __decorate([
  43120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43121. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43122. __decorate([
  43123. BABYLON.serialize("useSpecularOverAlpha")
  43124. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43125. __decorate([
  43126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43127. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43128. __decorate([
  43129. BABYLON.serialize("useReflectionOverAlpha")
  43130. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43131. __decorate([
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43133. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43134. __decorate([
  43135. BABYLON.serialize("disableLighting")
  43136. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43137. __decorate([
  43138. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43139. ], StandardMaterial.prototype, "disableLighting", void 0);
  43140. __decorate([
  43141. BABYLON.serialize("useObjectSpaceNormalMap")
  43142. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43143. __decorate([
  43144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43145. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43146. __decorate([
  43147. BABYLON.serialize("useParallax")
  43148. ], StandardMaterial.prototype, "_useParallax", void 0);
  43149. __decorate([
  43150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43151. ], StandardMaterial.prototype, "useParallax", void 0);
  43152. __decorate([
  43153. BABYLON.serialize("useParallaxOcclusion")
  43154. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43155. __decorate([
  43156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43157. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43158. __decorate([
  43159. BABYLON.serialize()
  43160. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43161. __decorate([
  43162. BABYLON.serialize("roughness")
  43163. ], StandardMaterial.prototype, "_roughness", void 0);
  43164. __decorate([
  43165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43166. ], StandardMaterial.prototype, "roughness", void 0);
  43167. __decorate([
  43168. BABYLON.serialize()
  43169. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43170. __decorate([
  43171. BABYLON.serialize()
  43172. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43173. __decorate([
  43174. BABYLON.serialize()
  43175. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43176. __decorate([
  43177. BABYLON.serialize("useLightmapAsShadowmap")
  43178. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43179. __decorate([
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43181. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43182. __decorate([
  43183. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43184. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43185. __decorate([
  43186. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43187. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43188. __decorate([
  43189. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43190. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43191. __decorate([
  43192. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43193. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43194. __decorate([
  43195. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43196. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43197. __decorate([
  43198. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43199. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43200. __decorate([
  43201. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43202. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43203. __decorate([
  43204. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43205. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43206. __decorate([
  43207. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43208. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43209. __decorate([
  43210. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43211. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43212. __decorate([
  43213. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43214. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43215. __decorate([
  43216. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43217. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43218. __decorate([
  43219. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43220. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43221. __decorate([
  43222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43223. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43224. __decorate([
  43225. BABYLON.serialize("maxSimultaneousLights")
  43226. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43227. __decorate([
  43228. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43229. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43230. __decorate([
  43231. BABYLON.serialize("invertNormalMapX")
  43232. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43233. __decorate([
  43234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43235. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43236. __decorate([
  43237. BABYLON.serialize("invertNormalMapY")
  43238. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43239. __decorate([
  43240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43241. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43242. __decorate([
  43243. BABYLON.serialize("twoSidedLighting")
  43244. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43245. __decorate([
  43246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43247. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43248. __decorate([
  43249. BABYLON.serialize()
  43250. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43251. return StandardMaterial;
  43252. }(BABYLON.PushMaterial));
  43253. BABYLON.StandardMaterial = StandardMaterial;
  43254. })(BABYLON || (BABYLON = {}));
  43255. //# sourceMappingURL=babylon.standardMaterial.js.map
  43256. var BABYLON;
  43257. (function (BABYLON) {
  43258. /**
  43259. * Manages the defines for the PBR Material.
  43260. * @hiddenChildren
  43261. */
  43262. var PBRMaterialDefines = /** @class */ (function (_super) {
  43263. __extends(PBRMaterialDefines, _super);
  43264. /**
  43265. * Initializes the PBR Material defines.
  43266. */
  43267. function PBRMaterialDefines() {
  43268. var _this = _super.call(this) || this;
  43269. _this.PBR = true;
  43270. _this.MAINUV1 = false;
  43271. _this.MAINUV2 = false;
  43272. _this.UV1 = false;
  43273. _this.UV2 = false;
  43274. _this.ALBEDO = false;
  43275. _this.ALBEDODIRECTUV = 0;
  43276. _this.VERTEXCOLOR = false;
  43277. _this.AMBIENT = false;
  43278. _this.AMBIENTDIRECTUV = 0;
  43279. _this.AMBIENTINGRAYSCALE = false;
  43280. _this.OPACITY = false;
  43281. _this.VERTEXALPHA = false;
  43282. _this.OPACITYDIRECTUV = 0;
  43283. _this.OPACITYRGB = false;
  43284. _this.ALPHATEST = false;
  43285. _this.DEPTHPREPASS = false;
  43286. _this.ALPHABLEND = false;
  43287. _this.ALPHAFROMALBEDO = false;
  43288. _this.ALPHATESTVALUE = "0.5";
  43289. _this.SPECULAROVERALPHA = false;
  43290. _this.RADIANCEOVERALPHA = false;
  43291. _this.ALPHAFRESNEL = false;
  43292. _this.LINEARALPHAFRESNEL = false;
  43293. _this.PREMULTIPLYALPHA = false;
  43294. _this.EMISSIVE = false;
  43295. _this.EMISSIVEDIRECTUV = 0;
  43296. _this.REFLECTIVITY = false;
  43297. _this.REFLECTIVITYDIRECTUV = 0;
  43298. _this.SPECULARTERM = false;
  43299. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43300. _this.MICROSURFACEAUTOMATIC = false;
  43301. _this.LODBASEDMICROSFURACE = false;
  43302. _this.MICROSURFACEMAP = false;
  43303. _this.MICROSURFACEMAPDIRECTUV = 0;
  43304. _this.METALLICWORKFLOW = false;
  43305. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43306. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43307. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43308. _this.AOSTOREINMETALMAPRED = false;
  43309. _this.ENVIRONMENTBRDF = false;
  43310. _this.NORMAL = false;
  43311. _this.TANGENT = false;
  43312. _this.BUMP = false;
  43313. _this.BUMPDIRECTUV = 0;
  43314. _this.OBJECTSPACE_NORMALMAP = false;
  43315. _this.PARALLAX = false;
  43316. _this.PARALLAXOCCLUSION = false;
  43317. _this.NORMALXYSCALE = true;
  43318. _this.LIGHTMAP = false;
  43319. _this.LIGHTMAPDIRECTUV = 0;
  43320. _this.USELIGHTMAPASSHADOWMAP = false;
  43321. _this.GAMMALIGHTMAP = false;
  43322. _this.REFLECTION = false;
  43323. _this.REFLECTIONMAP_3D = false;
  43324. _this.REFLECTIONMAP_SPHERICAL = false;
  43325. _this.REFLECTIONMAP_PLANAR = false;
  43326. _this.REFLECTIONMAP_CUBIC = false;
  43327. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43328. _this.REFLECTIONMAP_PROJECTION = false;
  43329. _this.REFLECTIONMAP_SKYBOX = false;
  43330. _this.REFLECTIONMAP_EXPLICIT = false;
  43331. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43332. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43333. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43334. _this.INVERTCUBICMAP = false;
  43335. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43336. _this.USESPHERICALINVERTEX = false;
  43337. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43338. _this.LODINREFLECTIONALPHA = false;
  43339. _this.GAMMAREFLECTION = false;
  43340. _this.RGBDREFLECTION = false;
  43341. _this.RADIANCEOCCLUSION = false;
  43342. _this.HORIZONOCCLUSION = false;
  43343. _this.REFRACTION = false;
  43344. _this.REFRACTIONMAP_3D = false;
  43345. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43346. _this.LODINREFRACTIONALPHA = false;
  43347. _this.GAMMAREFRACTION = false;
  43348. _this.RGBDREFRACTION = false;
  43349. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43350. _this.INSTANCES = false;
  43351. _this.NUM_BONE_INFLUENCERS = 0;
  43352. _this.BonesPerMesh = 0;
  43353. _this.NONUNIFORMSCALING = false;
  43354. _this.MORPHTARGETS = false;
  43355. _this.MORPHTARGETS_NORMAL = false;
  43356. _this.MORPHTARGETS_TANGENT = false;
  43357. _this.NUM_MORPH_INFLUENCERS = 0;
  43358. _this.IMAGEPROCESSING = false;
  43359. _this.VIGNETTE = false;
  43360. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43361. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43362. _this.TONEMAPPING = false;
  43363. _this.CONTRAST = false;
  43364. _this.COLORCURVES = false;
  43365. _this.COLORGRADING = false;
  43366. _this.COLORGRADING3D = false;
  43367. _this.SAMPLER3DGREENDEPTH = false;
  43368. _this.SAMPLER3DBGRMAP = false;
  43369. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43370. _this.EXPOSURE = false;
  43371. _this.USEPHYSICALLIGHTFALLOFF = false;
  43372. _this.TWOSIDEDLIGHTING = false;
  43373. _this.SHADOWFLOAT = false;
  43374. _this.CLIPPLANE = false;
  43375. _this.POINTSIZE = false;
  43376. _this.FOG = false;
  43377. _this.LOGARITHMICDEPTH = false;
  43378. _this.FORCENORMALFORWARD = false;
  43379. _this.SPECULARAA = false;
  43380. _this.UNLIT = false;
  43381. _this.rebuild();
  43382. return _this;
  43383. }
  43384. /**
  43385. * Resets the PBR Material defines.
  43386. */
  43387. PBRMaterialDefines.prototype.reset = function () {
  43388. _super.prototype.reset.call(this);
  43389. this.ALPHATESTVALUE = "0.5";
  43390. this.PBR = true;
  43391. };
  43392. return PBRMaterialDefines;
  43393. }(BABYLON.MaterialDefines));
  43394. /**
  43395. * The Physically based material base class of BJS.
  43396. *
  43397. * This offers the main features of a standard PBR material.
  43398. * For more information, please refer to the documentation :
  43399. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43400. */
  43401. var PBRBaseMaterial = /** @class */ (function (_super) {
  43402. __extends(PBRBaseMaterial, _super);
  43403. /**
  43404. * Instantiates a new PBRMaterial instance.
  43405. *
  43406. * @param name The material name
  43407. * @param scene The scene the material will be use in.
  43408. */
  43409. function PBRBaseMaterial(name, scene) {
  43410. var _this = _super.call(this, name, scene) || this;
  43411. /**
  43412. * Intensity of the direct lights e.g. the four lights available in your scene.
  43413. * This impacts both the direct diffuse and specular highlights.
  43414. */
  43415. _this._directIntensity = 1.0;
  43416. /**
  43417. * Intensity of the emissive part of the material.
  43418. * This helps controlling the emissive effect without modifying the emissive color.
  43419. */
  43420. _this._emissiveIntensity = 1.0;
  43421. /**
  43422. * Intensity of the environment e.g. how much the environment will light the object
  43423. * either through harmonics for rough material or through the refelction for shiny ones.
  43424. */
  43425. _this._environmentIntensity = 1.0;
  43426. /**
  43427. * This is a special control allowing the reduction of the specular highlights coming from the
  43428. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43429. */
  43430. _this._specularIntensity = 1.0;
  43431. /**
  43432. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43433. */
  43434. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43435. /**
  43436. * Debug Control allowing disabling the bump map on this material.
  43437. */
  43438. _this._disableBumpMap = false;
  43439. /**
  43440. * AKA Occlusion Texture Intensity in other nomenclature.
  43441. */
  43442. _this._ambientTextureStrength = 1.0;
  43443. /**
  43444. * The color of a material in ambient lighting.
  43445. */
  43446. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43447. /**
  43448. * AKA Diffuse Color in other nomenclature.
  43449. */
  43450. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43451. /**
  43452. * AKA Specular Color in other nomenclature.
  43453. */
  43454. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43455. /**
  43456. * The color applied when light is reflected from a material.
  43457. */
  43458. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43459. /**
  43460. * The color applied when light is emitted from a material.
  43461. */
  43462. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43463. /**
  43464. * AKA Glossiness in other nomenclature.
  43465. */
  43466. _this._microSurface = 0.9;
  43467. /**
  43468. * source material index of refraction (IOR)' / 'destination material IOR.
  43469. */
  43470. _this._indexOfRefraction = 0.66;
  43471. /**
  43472. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43473. */
  43474. _this._invertRefractionY = false;
  43475. /**
  43476. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43477. * Materials half opaque for instance using refraction could benefit from this control.
  43478. */
  43479. _this._linkRefractionWithTransparency = false;
  43480. /**
  43481. * Specifies that the material will use the light map as a show map.
  43482. */
  43483. _this._useLightmapAsShadowmap = false;
  43484. /**
  43485. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43486. * makes the reflect vector face the model (under horizon).
  43487. */
  43488. _this._useHorizonOcclusion = true;
  43489. /**
  43490. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43491. * too much the area relying on ambient texture to define their ambient occlusion.
  43492. */
  43493. _this._useRadianceOcclusion = true;
  43494. /**
  43495. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43496. */
  43497. _this._useAlphaFromAlbedoTexture = false;
  43498. /**
  43499. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43500. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43501. */
  43502. _this._useSpecularOverAlpha = true;
  43503. /**
  43504. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43505. */
  43506. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43507. /**
  43508. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43509. */
  43510. _this._useRoughnessFromMetallicTextureAlpha = true;
  43511. /**
  43512. * Specifies if the metallic texture contains the roughness information in its green channel.
  43513. */
  43514. _this._useRoughnessFromMetallicTextureGreen = false;
  43515. /**
  43516. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43517. */
  43518. _this._useMetallnessFromMetallicTextureBlue = false;
  43519. /**
  43520. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43521. */
  43522. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43523. /**
  43524. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43525. */
  43526. _this._useAmbientInGrayScale = false;
  43527. /**
  43528. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43529. * The material will try to infer what glossiness each pixel should be.
  43530. */
  43531. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43532. /**
  43533. * BJS is using an harcoded light falloff based on a manually sets up range.
  43534. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43535. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43536. */
  43537. _this._usePhysicalLightFalloff = true;
  43538. /**
  43539. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43540. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43541. */
  43542. _this._useRadianceOverAlpha = true;
  43543. /**
  43544. * Allows using an object space normal map (instead of tangent space).
  43545. */
  43546. _this._useObjectSpaceNormalMap = false;
  43547. /**
  43548. * Allows using the bump map in parallax mode.
  43549. */
  43550. _this._useParallax = false;
  43551. /**
  43552. * Allows using the bump map in parallax occlusion mode.
  43553. */
  43554. _this._useParallaxOcclusion = false;
  43555. /**
  43556. * Controls the scale bias of the parallax mode.
  43557. */
  43558. _this._parallaxScaleBias = 0.05;
  43559. /**
  43560. * If sets to true, disables all the lights affecting the material.
  43561. */
  43562. _this._disableLighting = false;
  43563. /**
  43564. * Number of Simultaneous lights allowed on the material.
  43565. */
  43566. _this._maxSimultaneousLights = 4;
  43567. /**
  43568. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43569. */
  43570. _this._invertNormalMapX = false;
  43571. /**
  43572. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43573. */
  43574. _this._invertNormalMapY = false;
  43575. /**
  43576. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43577. */
  43578. _this._twoSidedLighting = false;
  43579. /**
  43580. * Defines the alpha limits in alpha test mode.
  43581. */
  43582. _this._alphaCutOff = 0.4;
  43583. /**
  43584. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43585. */
  43586. _this._forceAlphaTest = false;
  43587. /**
  43588. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43589. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43590. */
  43591. _this._useAlphaFresnel = false;
  43592. /**
  43593. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43594. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43595. */
  43596. _this._useLinearAlphaFresnel = false;
  43597. /**
  43598. * The transparency mode of the material.
  43599. */
  43600. _this._transparencyMode = null;
  43601. /**
  43602. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43603. * from cos thetav and roughness:
  43604. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43605. */
  43606. _this._environmentBRDFTexture = null;
  43607. /**
  43608. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43609. */
  43610. _this._forceIrradianceInFragment = false;
  43611. /**
  43612. * Force normal to face away from face.
  43613. */
  43614. _this._forceNormalForward = false;
  43615. /**
  43616. * Enables specular anti aliasing in the PBR shader.
  43617. * It will both interacts on the Geometry for analytical and IBL lighting.
  43618. * It also prefilter the roughness map based on the bump values.
  43619. */
  43620. _this._enableSpecularAntiAliasing = false;
  43621. /**
  43622. * Stores the available render targets.
  43623. */
  43624. _this._renderTargets = new BABYLON.SmartArray(16);
  43625. /**
  43626. * Sets the global ambient color for the material used in lighting calculations.
  43627. */
  43628. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43629. /**
  43630. * If set to true, no lighting calculations will be applied.
  43631. */
  43632. _this._unlit = false;
  43633. // Setup the default processing configuration to the scene.
  43634. _this._attachImageProcessingConfiguration(null);
  43635. _this.getRenderTargetTextures = function () {
  43636. _this._renderTargets.reset();
  43637. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43638. _this._renderTargets.push(_this._reflectionTexture);
  43639. }
  43640. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43641. _this._renderTargets.push(_this._refractionTexture);
  43642. }
  43643. return _this._renderTargets;
  43644. };
  43645. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43646. return _this;
  43647. }
  43648. /**
  43649. * Attaches a new image processing configuration to the PBR Material.
  43650. * @param configuration
  43651. */
  43652. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43653. var _this = this;
  43654. if (configuration === this._imageProcessingConfiguration) {
  43655. return;
  43656. }
  43657. // Detaches observer.
  43658. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43659. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43660. }
  43661. // Pick the scene configuration if needed.
  43662. if (!configuration) {
  43663. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43664. }
  43665. else {
  43666. this._imageProcessingConfiguration = configuration;
  43667. }
  43668. // Attaches observer.
  43669. if (this._imageProcessingConfiguration) {
  43670. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43671. _this._markAllSubMeshesAsImageProcessingDirty();
  43672. });
  43673. }
  43674. };
  43675. /**
  43676. * Gets the name of the material class.
  43677. */
  43678. PBRBaseMaterial.prototype.getClassName = function () {
  43679. return "PBRBaseMaterial";
  43680. };
  43681. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43682. /**
  43683. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43684. */
  43685. get: function () {
  43686. return this._useLogarithmicDepth;
  43687. },
  43688. /**
  43689. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43690. */
  43691. set: function (value) {
  43692. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43693. },
  43694. enumerable: true,
  43695. configurable: true
  43696. });
  43697. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43698. /**
  43699. * Gets the current transparency mode.
  43700. */
  43701. get: function () {
  43702. return this._transparencyMode;
  43703. },
  43704. /**
  43705. * Sets the transparency mode of the material.
  43706. *
  43707. * | Value | Type | Description |
  43708. * | ----- | ----------------------------------- | ----------- |
  43709. * | 0 | OPAQUE | |
  43710. * | 1 | ALPHATEST | |
  43711. * | 2 | ALPHABLEND | |
  43712. * | 3 | ALPHATESTANDBLEND | |
  43713. *
  43714. */
  43715. set: function (value) {
  43716. if (this._transparencyMode === value) {
  43717. return;
  43718. }
  43719. this._transparencyMode = value;
  43720. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43721. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43722. },
  43723. enumerable: true,
  43724. configurable: true
  43725. });
  43726. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43727. /**
  43728. * Returns true if alpha blending should be disabled.
  43729. */
  43730. get: function () {
  43731. return (this._linkRefractionWithTransparency ||
  43732. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43733. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43734. },
  43735. enumerable: true,
  43736. configurable: true
  43737. });
  43738. /**
  43739. * Specifies whether or not this material should be rendered in alpha blend mode.
  43740. */
  43741. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43742. if (this._disableAlphaBlending) {
  43743. return false;
  43744. }
  43745. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43746. };
  43747. /**
  43748. * Specifies if the mesh will require alpha blending.
  43749. * @param mesh - BJS mesh.
  43750. */
  43751. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43752. if (this._disableAlphaBlending) {
  43753. return false;
  43754. }
  43755. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43756. };
  43757. /**
  43758. * Specifies whether or not this material should be rendered in alpha test mode.
  43759. */
  43760. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43761. if (this._forceAlphaTest) {
  43762. return true;
  43763. }
  43764. if (this._linkRefractionWithTransparency) {
  43765. return false;
  43766. }
  43767. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43768. };
  43769. /**
  43770. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43771. */
  43772. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43773. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43774. };
  43775. /**
  43776. * Gets the texture used for the alpha test.
  43777. */
  43778. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43779. return this._albedoTexture;
  43780. };
  43781. /**
  43782. * Specifies that the submesh is ready to be used.
  43783. * @param mesh - BJS mesh.
  43784. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43785. * @param useInstances - Specifies that instances should be used.
  43786. * @returns - boolean indicating that the submesh is ready or not.
  43787. */
  43788. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43789. if (subMesh.effect && this.isFrozen) {
  43790. if (this._wasPreviouslyReady) {
  43791. return true;
  43792. }
  43793. }
  43794. if (!subMesh._materialDefines) {
  43795. subMesh._materialDefines = new PBRMaterialDefines();
  43796. }
  43797. var defines = subMesh._materialDefines;
  43798. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43799. if (defines._renderId === this.getScene().getRenderId()) {
  43800. return true;
  43801. }
  43802. }
  43803. var scene = this.getScene();
  43804. var engine = scene.getEngine();
  43805. if (defines._areTexturesDirty) {
  43806. if (scene.texturesEnabled) {
  43807. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43808. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43809. return false;
  43810. }
  43811. }
  43812. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43813. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43814. return false;
  43815. }
  43816. }
  43817. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43818. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43819. return false;
  43820. }
  43821. }
  43822. var reflectionTexture = this._getReflectionTexture();
  43823. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43824. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43825. return false;
  43826. }
  43827. }
  43828. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43829. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43830. return false;
  43831. }
  43832. }
  43833. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43834. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43835. return false;
  43836. }
  43837. }
  43838. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43839. if (this._metallicTexture) {
  43840. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43841. return false;
  43842. }
  43843. }
  43844. else if (this._reflectivityTexture) {
  43845. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43846. return false;
  43847. }
  43848. }
  43849. if (this._microSurfaceTexture) {
  43850. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43851. return false;
  43852. }
  43853. }
  43854. }
  43855. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43856. // Bump texture cannot be not blocking.
  43857. if (!this._bumpTexture.isReady()) {
  43858. return false;
  43859. }
  43860. }
  43861. var refractionTexture = this._getRefractionTexture();
  43862. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43863. if (!refractionTexture.isReadyOrNotBlocking()) {
  43864. return false;
  43865. }
  43866. }
  43867. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43868. // This is blocking.
  43869. if (!this._environmentBRDFTexture.isReady()) {
  43870. return false;
  43871. }
  43872. }
  43873. }
  43874. }
  43875. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43876. if (!this._imageProcessingConfiguration.isReady()) {
  43877. return false;
  43878. }
  43879. }
  43880. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43881. mesh.createNormals(true);
  43882. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43883. }
  43884. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43885. if (effect) {
  43886. scene.resetCachedMaterial();
  43887. subMesh.setEffect(effect, defines);
  43888. this.buildUniformLayout();
  43889. }
  43890. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43891. return false;
  43892. }
  43893. defines._renderId = scene.getRenderId();
  43894. this._wasPreviouslyReady = true;
  43895. return true;
  43896. };
  43897. /**
  43898. * Specifies if the material uses metallic roughness workflow.
  43899. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43900. */
  43901. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43902. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43903. return true;
  43904. }
  43905. return false;
  43906. };
  43907. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43908. if (onCompiled === void 0) { onCompiled = null; }
  43909. if (onError === void 0) { onError = null; }
  43910. if (useInstances === void 0) { useInstances = null; }
  43911. if (useClipPlane === void 0) { useClipPlane = null; }
  43912. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43913. if (!defines.isDirty) {
  43914. return null;
  43915. }
  43916. defines.markAsProcessed();
  43917. var scene = this.getScene();
  43918. var engine = scene.getEngine();
  43919. // Fallbacks
  43920. var fallbacks = new BABYLON.EffectFallbacks();
  43921. var fallbackRank = 0;
  43922. if (defines.USESPHERICALINVERTEX) {
  43923. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43924. }
  43925. if (defines.FOG) {
  43926. fallbacks.addFallback(fallbackRank, "FOG");
  43927. }
  43928. if (defines.SPECULARAA) {
  43929. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43930. }
  43931. if (defines.POINTSIZE) {
  43932. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43933. }
  43934. if (defines.LOGARITHMICDEPTH) {
  43935. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43936. }
  43937. if (defines.PARALLAX) {
  43938. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43939. }
  43940. if (defines.PARALLAXOCCLUSION) {
  43941. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43942. }
  43943. if (defines.ENVIRONMENTBRDF) {
  43944. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43945. }
  43946. if (defines.TANGENT) {
  43947. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43948. }
  43949. if (defines.BUMP) {
  43950. fallbacks.addFallback(fallbackRank++, "BUMP");
  43951. }
  43952. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43953. if (defines.SPECULARTERM) {
  43954. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43955. }
  43956. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43957. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43958. }
  43959. if (defines.LIGHTMAP) {
  43960. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43961. }
  43962. if (defines.NORMAL) {
  43963. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43964. }
  43965. if (defines.AMBIENT) {
  43966. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43967. }
  43968. if (defines.EMISSIVE) {
  43969. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43970. }
  43971. if (defines.VERTEXCOLOR) {
  43972. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43973. }
  43974. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43975. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43976. }
  43977. if (defines.MORPHTARGETS) {
  43978. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43979. }
  43980. //Attributes
  43981. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43982. if (defines.NORMAL) {
  43983. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43984. }
  43985. if (defines.TANGENT) {
  43986. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43987. }
  43988. if (defines.UV1) {
  43989. attribs.push(BABYLON.VertexBuffer.UVKind);
  43990. }
  43991. if (defines.UV2) {
  43992. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43993. }
  43994. if (defines.VERTEXCOLOR) {
  43995. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43996. }
  43997. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43998. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43999. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44000. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44001. "vFogInfos", "vFogColor", "pointSize",
  44002. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44003. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44004. "mBones",
  44005. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44006. "vLightingIntensity",
  44007. "logarithmicDepthConstant",
  44008. "vSphericalX", "vSphericalY", "vSphericalZ",
  44009. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44010. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44011. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44012. "vTangentSpaceParams"
  44013. ];
  44014. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44015. "bumpSampler", "lightmapSampler", "opacitySampler",
  44016. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44017. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44018. "microSurfaceSampler", "environmentBrdfSampler"];
  44019. var uniformBuffers = ["Material", "Scene"];
  44020. if (BABYLON.ImageProcessingConfiguration) {
  44021. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44022. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44023. }
  44024. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44025. uniformsNames: uniforms,
  44026. uniformBuffersNames: uniformBuffers,
  44027. samplers: samplers,
  44028. defines: defines,
  44029. maxSimultaneousLights: this._maxSimultaneousLights
  44030. });
  44031. var join = defines.toString();
  44032. return engine.createEffect("pbr", {
  44033. attributes: attribs,
  44034. uniformsNames: uniforms,
  44035. uniformBuffersNames: uniformBuffers,
  44036. samplers: samplers,
  44037. defines: join,
  44038. fallbacks: fallbacks,
  44039. onCompiled: onCompiled,
  44040. onError: onError,
  44041. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44042. }, engine);
  44043. };
  44044. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44045. if (useInstances === void 0) { useInstances = null; }
  44046. if (useClipPlane === void 0) { useClipPlane = null; }
  44047. var scene = this.getScene();
  44048. var engine = scene.getEngine();
  44049. // Lights
  44050. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44051. defines._needNormals = true;
  44052. // Textures
  44053. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44054. if (defines._areTexturesDirty) {
  44055. defines._needUVs = false;
  44056. if (scene.texturesEnabled) {
  44057. if (scene.getEngine().getCaps().textureLOD) {
  44058. defines.LODBASEDMICROSFURACE = true;
  44059. }
  44060. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44061. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44062. }
  44063. else {
  44064. defines.ALBEDO = false;
  44065. }
  44066. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44067. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44068. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44069. }
  44070. else {
  44071. defines.AMBIENT = false;
  44072. }
  44073. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44074. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44075. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44076. }
  44077. else {
  44078. defines.OPACITY = false;
  44079. }
  44080. var reflectionTexture = this._getReflectionTexture();
  44081. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44082. defines.REFLECTION = true;
  44083. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44084. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44085. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44086. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44087. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44088. defines.INVERTCUBICMAP = true;
  44089. }
  44090. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44091. switch (reflectionTexture.coordinatesMode) {
  44092. case BABYLON.Texture.EXPLICIT_MODE:
  44093. defines.REFLECTIONMAP_EXPLICIT = true;
  44094. break;
  44095. case BABYLON.Texture.PLANAR_MODE:
  44096. defines.REFLECTIONMAP_PLANAR = true;
  44097. break;
  44098. case BABYLON.Texture.PROJECTION_MODE:
  44099. defines.REFLECTIONMAP_PROJECTION = true;
  44100. break;
  44101. case BABYLON.Texture.SKYBOX_MODE:
  44102. defines.REFLECTIONMAP_SKYBOX = true;
  44103. break;
  44104. case BABYLON.Texture.SPHERICAL_MODE:
  44105. defines.REFLECTIONMAP_SPHERICAL = true;
  44106. break;
  44107. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44108. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44109. break;
  44110. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44111. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44112. break;
  44113. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44114. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44115. break;
  44116. case BABYLON.Texture.CUBIC_MODE:
  44117. case BABYLON.Texture.INVCUBIC_MODE:
  44118. default:
  44119. defines.REFLECTIONMAP_CUBIC = true;
  44120. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44121. break;
  44122. }
  44123. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44124. if (reflectionTexture.sphericalPolynomial) {
  44125. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44126. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44127. defines.USESPHERICALINVERTEX = false;
  44128. }
  44129. else {
  44130. defines.USESPHERICALINVERTEX = true;
  44131. }
  44132. }
  44133. }
  44134. }
  44135. else {
  44136. defines.REFLECTION = false;
  44137. defines.REFLECTIONMAP_3D = false;
  44138. defines.REFLECTIONMAP_SPHERICAL = false;
  44139. defines.REFLECTIONMAP_PLANAR = false;
  44140. defines.REFLECTIONMAP_CUBIC = false;
  44141. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44142. defines.REFLECTIONMAP_PROJECTION = false;
  44143. defines.REFLECTIONMAP_SKYBOX = false;
  44144. defines.REFLECTIONMAP_EXPLICIT = false;
  44145. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44146. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44147. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44148. defines.INVERTCUBICMAP = false;
  44149. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44150. defines.USESPHERICALINVERTEX = false;
  44151. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44152. defines.LODINREFLECTIONALPHA = false;
  44153. defines.GAMMAREFLECTION = false;
  44154. defines.RGBDREFLECTION = false;
  44155. }
  44156. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44157. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44158. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44159. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44160. }
  44161. else {
  44162. defines.LIGHTMAP = false;
  44163. }
  44164. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44165. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44166. }
  44167. else {
  44168. defines.EMISSIVE = false;
  44169. }
  44170. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44171. if (this._metallicTexture) {
  44172. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44173. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44174. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44175. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44176. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44177. }
  44178. else if (this._reflectivityTexture) {
  44179. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44180. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44181. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44182. }
  44183. else {
  44184. defines.REFLECTIVITY = false;
  44185. }
  44186. if (this._microSurfaceTexture) {
  44187. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44188. }
  44189. else {
  44190. defines.MICROSURFACEMAP = false;
  44191. }
  44192. }
  44193. else {
  44194. defines.REFLECTIVITY = false;
  44195. defines.MICROSURFACEMAP = false;
  44196. }
  44197. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44198. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44199. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44200. defines.PARALLAX = true;
  44201. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44202. }
  44203. else {
  44204. defines.PARALLAX = false;
  44205. }
  44206. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44207. }
  44208. else {
  44209. defines.BUMP = false;
  44210. }
  44211. var refractionTexture = this._getRefractionTexture();
  44212. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44213. defines.REFRACTION = true;
  44214. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44215. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44216. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44217. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44218. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44219. if (this._linkRefractionWithTransparency) {
  44220. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44221. }
  44222. }
  44223. else {
  44224. defines.REFRACTION = false;
  44225. }
  44226. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44227. defines.ENVIRONMENTBRDF = true;
  44228. }
  44229. else {
  44230. defines.ENVIRONMENTBRDF = false;
  44231. }
  44232. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44233. defines.ALPHAFROMALBEDO = true;
  44234. }
  44235. else {
  44236. defines.ALPHAFROMALBEDO = false;
  44237. }
  44238. }
  44239. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44240. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44241. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44242. if (!this.backFaceCulling && this._twoSidedLighting) {
  44243. defines.TWOSIDEDLIGHTING = true;
  44244. }
  44245. else {
  44246. defines.TWOSIDEDLIGHTING = false;
  44247. }
  44248. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44249. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44250. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44251. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44252. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44253. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44254. }
  44255. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44256. this._imageProcessingConfiguration.prepareDefines(defines);
  44257. }
  44258. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44259. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44260. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44261. // Misc.
  44262. if (defines._areMiscDirty) {
  44263. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44264. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44265. }
  44266. // Values that need to be evaluated on every frame
  44267. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44268. // Attribs
  44269. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44270. };
  44271. /**
  44272. * Force shader compilation
  44273. */
  44274. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44275. var _this = this;
  44276. var localOptions = __assign({ clipPlane: false }, options);
  44277. var defines = new PBRMaterialDefines();
  44278. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44279. if (effect.isReady()) {
  44280. if (onCompiled) {
  44281. onCompiled(this);
  44282. }
  44283. }
  44284. else {
  44285. effect.onCompileObservable.add(function () {
  44286. if (onCompiled) {
  44287. onCompiled(_this);
  44288. }
  44289. });
  44290. }
  44291. };
  44292. /**
  44293. * Initializes the uniform buffer layout for the shader.
  44294. */
  44295. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44296. // Order is important !
  44297. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44298. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44299. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44300. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44301. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44302. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44303. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44304. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44305. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44306. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44307. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44308. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44309. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44310. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44311. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44312. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44313. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44314. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44315. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44316. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44317. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44318. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44319. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44320. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44321. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44322. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44323. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44324. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44325. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44326. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44327. this._uniformBuffer.addUniform("pointSize", 1);
  44328. this._uniformBuffer.create();
  44329. };
  44330. /**
  44331. * Unbinds the textures.
  44332. */
  44333. PBRBaseMaterial.prototype.unbind = function () {
  44334. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44335. this._uniformBuffer.setTexture("reflectionSampler", null);
  44336. }
  44337. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44338. this._uniformBuffer.setTexture("refractionSampler", null);
  44339. }
  44340. _super.prototype.unbind.call(this);
  44341. };
  44342. /**
  44343. * Binds the submesh data.
  44344. * @param world - The world matrix.
  44345. * @param mesh - The BJS mesh.
  44346. * @param subMesh - A submesh of the BJS mesh.
  44347. */
  44348. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44349. var scene = this.getScene();
  44350. var defines = subMesh._materialDefines;
  44351. if (!defines) {
  44352. return;
  44353. }
  44354. var effect = subMesh.effect;
  44355. if (!effect) {
  44356. return;
  44357. }
  44358. this._activeEffect = effect;
  44359. // Matrices
  44360. this.bindOnlyWorldMatrix(world);
  44361. // Normal Matrix
  44362. if (defines.OBJECTSPACE_NORMALMAP) {
  44363. world.toNormalMatrix(this._normalMatrix);
  44364. this.bindOnlyNormalMatrix(this._normalMatrix);
  44365. }
  44366. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44367. // Bones
  44368. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44369. var reflectionTexture = null;
  44370. if (mustRebind) {
  44371. this._uniformBuffer.bindToEffect(effect, "Material");
  44372. this.bindViewProjection(effect);
  44373. reflectionTexture = this._getReflectionTexture();
  44374. var refractionTexture = this._getRefractionTexture();
  44375. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44376. // Texture uniforms
  44377. if (scene.texturesEnabled) {
  44378. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44379. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44380. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44381. }
  44382. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44383. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44384. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44385. }
  44386. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44387. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44388. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44389. }
  44390. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44391. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44392. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44393. if (reflectionTexture.boundingBoxSize) {
  44394. var cubeTexture = reflectionTexture;
  44395. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44396. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44397. }
  44398. var polynomials = reflectionTexture.sphericalPolynomial;
  44399. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44400. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44401. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44402. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44403. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44404. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44405. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44406. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44407. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44408. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44409. }
  44410. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44411. }
  44412. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44413. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44414. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44415. }
  44416. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44417. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44418. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44419. }
  44420. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44421. if (this._metallicTexture) {
  44422. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44423. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44424. }
  44425. else if (this._reflectivityTexture) {
  44426. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44427. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44428. }
  44429. if (this._microSurfaceTexture) {
  44430. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44431. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44432. }
  44433. }
  44434. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44435. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44436. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44437. if (scene._mirroredCameraPosition) {
  44438. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44439. }
  44440. else {
  44441. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44442. }
  44443. }
  44444. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44445. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44446. var depth = 1.0;
  44447. if (!refractionTexture.isCube) {
  44448. if (refractionTexture.depth) {
  44449. depth = refractionTexture.depth;
  44450. }
  44451. }
  44452. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44453. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44454. }
  44455. }
  44456. // Point size
  44457. if (this.pointsCloud) {
  44458. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44459. }
  44460. // Colors
  44461. if (defines.METALLICWORKFLOW) {
  44462. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44463. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44464. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44465. }
  44466. else {
  44467. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44468. }
  44469. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44470. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44471. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44472. // Misc
  44473. this._lightingInfos.x = this._directIntensity;
  44474. this._lightingInfos.y = this._emissiveIntensity;
  44475. this._lightingInfos.z = this._environmentIntensity;
  44476. this._lightingInfos.w = this._specularIntensity;
  44477. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44478. }
  44479. // Textures
  44480. if (scene.texturesEnabled) {
  44481. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44482. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44483. }
  44484. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44485. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44486. }
  44487. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44488. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44489. }
  44490. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44491. if (defines.LODBASEDMICROSFURACE) {
  44492. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44493. }
  44494. else {
  44495. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44496. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44497. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44498. }
  44499. }
  44500. if (defines.ENVIRONMENTBRDF) {
  44501. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44502. }
  44503. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44504. if (defines.LODBASEDMICROSFURACE) {
  44505. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44506. }
  44507. else {
  44508. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44509. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44510. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44511. }
  44512. }
  44513. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44514. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44515. }
  44516. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44517. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44518. }
  44519. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44520. if (this._metallicTexture) {
  44521. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44522. }
  44523. else if (this._reflectivityTexture) {
  44524. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44525. }
  44526. if (this._microSurfaceTexture) {
  44527. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44528. }
  44529. }
  44530. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44531. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44532. }
  44533. }
  44534. // Clip plane
  44535. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44536. // Colors
  44537. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44538. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44539. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44540. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44541. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44542. }
  44543. if (mustRebind || !this.isFrozen) {
  44544. // Lights
  44545. if (scene.lightsEnabled && !this._disableLighting) {
  44546. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44547. }
  44548. // View
  44549. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44550. this.bindView(effect);
  44551. }
  44552. // Fog
  44553. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44554. // Morph targets
  44555. if (defines.NUM_MORPH_INFLUENCERS) {
  44556. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44557. }
  44558. // image processing
  44559. this._imageProcessingConfiguration.bind(this._activeEffect);
  44560. // Log. depth
  44561. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44562. }
  44563. this._uniformBuffer.update();
  44564. this._afterBind(mesh, this._activeEffect);
  44565. };
  44566. /**
  44567. * Returns the animatable textures.
  44568. * @returns - Array of animatable textures.
  44569. */
  44570. PBRBaseMaterial.prototype.getAnimatables = function () {
  44571. var results = [];
  44572. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44573. results.push(this._albedoTexture);
  44574. }
  44575. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44576. results.push(this._ambientTexture);
  44577. }
  44578. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44579. results.push(this._opacityTexture);
  44580. }
  44581. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44582. results.push(this._reflectionTexture);
  44583. }
  44584. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44585. results.push(this._emissiveTexture);
  44586. }
  44587. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44588. results.push(this._metallicTexture);
  44589. }
  44590. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44591. results.push(this._reflectivityTexture);
  44592. }
  44593. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44594. results.push(this._bumpTexture);
  44595. }
  44596. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44597. results.push(this._lightmapTexture);
  44598. }
  44599. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44600. results.push(this._refractionTexture);
  44601. }
  44602. return results;
  44603. };
  44604. /**
  44605. * Returns the texture used for reflections.
  44606. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44607. */
  44608. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44609. if (this._reflectionTexture) {
  44610. return this._reflectionTexture;
  44611. }
  44612. return this.getScene().environmentTexture;
  44613. };
  44614. /**
  44615. * Returns the texture used for refraction or null if none is used.
  44616. * @returns - Refection texture if present. If no refraction texture and refraction
  44617. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44618. */
  44619. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44620. if (this._refractionTexture) {
  44621. return this._refractionTexture;
  44622. }
  44623. if (this._linkRefractionWithTransparency) {
  44624. return this.getScene().environmentTexture;
  44625. }
  44626. return null;
  44627. };
  44628. /**
  44629. * Disposes the resources of the material.
  44630. * @param forceDisposeEffect - Forces the disposal of effects.
  44631. * @param forceDisposeTextures - Forces the disposal of all textures.
  44632. */
  44633. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44634. if (forceDisposeTextures) {
  44635. if (this._albedoTexture) {
  44636. this._albedoTexture.dispose();
  44637. }
  44638. if (this._ambientTexture) {
  44639. this._ambientTexture.dispose();
  44640. }
  44641. if (this._opacityTexture) {
  44642. this._opacityTexture.dispose();
  44643. }
  44644. if (this._reflectionTexture) {
  44645. this._reflectionTexture.dispose();
  44646. }
  44647. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44648. this._environmentBRDFTexture.dispose();
  44649. }
  44650. if (this._emissiveTexture) {
  44651. this._emissiveTexture.dispose();
  44652. }
  44653. if (this._metallicTexture) {
  44654. this._metallicTexture.dispose();
  44655. }
  44656. if (this._reflectivityTexture) {
  44657. this._reflectivityTexture.dispose();
  44658. }
  44659. if (this._bumpTexture) {
  44660. this._bumpTexture.dispose();
  44661. }
  44662. if (this._lightmapTexture) {
  44663. this._lightmapTexture.dispose();
  44664. }
  44665. if (this._refractionTexture) {
  44666. this._refractionTexture.dispose();
  44667. }
  44668. }
  44669. this._renderTargets.dispose();
  44670. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44671. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44672. }
  44673. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44674. };
  44675. /**
  44676. * Stores the reflectivity values based on metallic roughness workflow.
  44677. */
  44678. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44679. __decorate([
  44680. BABYLON.serializeAsImageProcessingConfiguration()
  44681. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44682. __decorate([
  44683. BABYLON.serialize()
  44684. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44685. __decorate([
  44686. BABYLON.serialize()
  44687. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44688. return PBRBaseMaterial;
  44689. }(BABYLON.PushMaterial));
  44690. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44691. })(BABYLON || (BABYLON = {}));
  44692. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44693. var BABYLON;
  44694. (function (BABYLON) {
  44695. /**
  44696. * The Physically based simple base material of BJS.
  44697. *
  44698. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44699. * It is used as the base class for both the specGloss and metalRough conventions.
  44700. */
  44701. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44702. __extends(PBRBaseSimpleMaterial, _super);
  44703. /**
  44704. * Instantiates a new PBRMaterial instance.
  44705. *
  44706. * @param name The material name
  44707. * @param scene The scene the material will be use in.
  44708. */
  44709. function PBRBaseSimpleMaterial(name, scene) {
  44710. var _this = _super.call(this, name, scene) || this;
  44711. /**
  44712. * Number of Simultaneous lights allowed on the material.
  44713. */
  44714. _this.maxSimultaneousLights = 4;
  44715. /**
  44716. * If sets to true, disables all the lights affecting the material.
  44717. */
  44718. _this.disableLighting = false;
  44719. /**
  44720. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44721. */
  44722. _this.invertNormalMapX = false;
  44723. /**
  44724. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44725. */
  44726. _this.invertNormalMapY = false;
  44727. /**
  44728. * Emissivie color used to self-illuminate the model.
  44729. */
  44730. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44731. /**
  44732. * Occlusion Channel Strenght.
  44733. */
  44734. _this.occlusionStrength = 1.0;
  44735. _this.useLightmapAsShadowmap = false;
  44736. _this._useAlphaFromAlbedoTexture = true;
  44737. _this._useAmbientInGrayScale = true;
  44738. return _this;
  44739. }
  44740. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44741. /**
  44742. * Gets the current double sided mode.
  44743. */
  44744. get: function () {
  44745. return this._twoSidedLighting;
  44746. },
  44747. /**
  44748. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44749. */
  44750. set: function (value) {
  44751. if (this._twoSidedLighting === value) {
  44752. return;
  44753. }
  44754. this._twoSidedLighting = value;
  44755. this.backFaceCulling = !value;
  44756. this._markAllSubMeshesAsTexturesDirty();
  44757. },
  44758. enumerable: true,
  44759. configurable: true
  44760. });
  44761. /**
  44762. * Return the active textures of the material.
  44763. */
  44764. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44765. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44766. if (this.environmentTexture) {
  44767. activeTextures.push(this.environmentTexture);
  44768. }
  44769. if (this.normalTexture) {
  44770. activeTextures.push(this.normalTexture);
  44771. }
  44772. if (this.emissiveTexture) {
  44773. activeTextures.push(this.emissiveTexture);
  44774. }
  44775. if (this.occlusionTexture) {
  44776. activeTextures.push(this.occlusionTexture);
  44777. }
  44778. if (this.lightmapTexture) {
  44779. activeTextures.push(this.lightmapTexture);
  44780. }
  44781. return activeTextures;
  44782. };
  44783. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44784. if (_super.prototype.hasTexture.call(this, texture)) {
  44785. return true;
  44786. }
  44787. if (this.lightmapTexture === texture) {
  44788. return true;
  44789. }
  44790. return false;
  44791. };
  44792. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44793. return "PBRBaseSimpleMaterial";
  44794. };
  44795. __decorate([
  44796. BABYLON.serialize(),
  44797. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44798. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44799. __decorate([
  44800. BABYLON.serialize(),
  44801. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44802. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44803. __decorate([
  44804. BABYLON.serializeAsTexture(),
  44805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44806. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44807. __decorate([
  44808. BABYLON.serialize(),
  44809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44810. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44811. __decorate([
  44812. BABYLON.serialize(),
  44813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44814. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44815. __decorate([
  44816. BABYLON.serializeAsTexture(),
  44817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44818. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44819. __decorate([
  44820. BABYLON.serializeAsColor3("emissive"),
  44821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44822. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44823. __decorate([
  44824. BABYLON.serializeAsTexture(),
  44825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44826. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44827. __decorate([
  44828. BABYLON.serialize(),
  44829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44830. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44831. __decorate([
  44832. BABYLON.serializeAsTexture(),
  44833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44834. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44835. __decorate([
  44836. BABYLON.serialize(),
  44837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44838. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44839. __decorate([
  44840. BABYLON.serialize()
  44841. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44842. __decorate([
  44843. BABYLON.serializeAsTexture(),
  44844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44845. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44846. __decorate([
  44847. BABYLON.serialize(),
  44848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44849. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44850. return PBRBaseSimpleMaterial;
  44851. }(BABYLON.PBRBaseMaterial));
  44852. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44853. })(BABYLON || (BABYLON = {}));
  44854. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44855. var BABYLON;
  44856. (function (BABYLON) {
  44857. /**
  44858. * The Physically based material of BJS.
  44859. *
  44860. * This offers the main features of a standard PBR material.
  44861. * For more information, please refer to the documentation :
  44862. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44863. */
  44864. var PBRMaterial = /** @class */ (function (_super) {
  44865. __extends(PBRMaterial, _super);
  44866. /**
  44867. * Instantiates a new PBRMaterial instance.
  44868. *
  44869. * @param name The material name
  44870. * @param scene The scene the material will be use in.
  44871. */
  44872. function PBRMaterial(name, scene) {
  44873. var _this = _super.call(this, name, scene) || this;
  44874. /**
  44875. * Intensity of the direct lights e.g. the four lights available in your scene.
  44876. * This impacts both the direct diffuse and specular highlights.
  44877. */
  44878. _this.directIntensity = 1.0;
  44879. /**
  44880. * Intensity of the emissive part of the material.
  44881. * This helps controlling the emissive effect without modifying the emissive color.
  44882. */
  44883. _this.emissiveIntensity = 1.0;
  44884. /**
  44885. * Intensity of the environment e.g. how much the environment will light the object
  44886. * either through harmonics for rough material or through the refelction for shiny ones.
  44887. */
  44888. _this.environmentIntensity = 1.0;
  44889. /**
  44890. * This is a special control allowing the reduction of the specular highlights coming from the
  44891. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44892. */
  44893. _this.specularIntensity = 1.0;
  44894. /**
  44895. * Debug Control allowing disabling the bump map on this material.
  44896. */
  44897. _this.disableBumpMap = false;
  44898. /**
  44899. * AKA Occlusion Texture Intensity in other nomenclature.
  44900. */
  44901. _this.ambientTextureStrength = 1.0;
  44902. /**
  44903. * The color of a material in ambient lighting.
  44904. */
  44905. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44906. /**
  44907. * AKA Diffuse Color in other nomenclature.
  44908. */
  44909. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44910. /**
  44911. * AKA Specular Color in other nomenclature.
  44912. */
  44913. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44914. /**
  44915. * The color reflected from the material.
  44916. */
  44917. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44918. /**
  44919. * The color emitted from the material.
  44920. */
  44921. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44922. /**
  44923. * AKA Glossiness in other nomenclature.
  44924. */
  44925. _this.microSurface = 1.0;
  44926. /**
  44927. * source material index of refraction (IOR)' / 'destination material IOR.
  44928. */
  44929. _this.indexOfRefraction = 0.66;
  44930. /**
  44931. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44932. */
  44933. _this.invertRefractionY = false;
  44934. /**
  44935. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44936. * Materials half opaque for instance using refraction could benefit from this control.
  44937. */
  44938. _this.linkRefractionWithTransparency = false;
  44939. _this.useLightmapAsShadowmap = false;
  44940. /**
  44941. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44942. */
  44943. _this.useAlphaFromAlbedoTexture = false;
  44944. /**
  44945. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44946. */
  44947. _this.forceAlphaTest = false;
  44948. /**
  44949. * Defines the alpha limits in alpha test mode.
  44950. */
  44951. _this.alphaCutOff = 0.4;
  44952. /**
  44953. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44954. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44955. */
  44956. _this.useSpecularOverAlpha = true;
  44957. /**
  44958. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44959. */
  44960. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44961. /**
  44962. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44963. */
  44964. _this.useRoughnessFromMetallicTextureAlpha = true;
  44965. /**
  44966. * Specifies if the metallic texture contains the roughness information in its green channel.
  44967. */
  44968. _this.useRoughnessFromMetallicTextureGreen = false;
  44969. /**
  44970. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44971. */
  44972. _this.useMetallnessFromMetallicTextureBlue = false;
  44973. /**
  44974. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44975. */
  44976. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44977. /**
  44978. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44979. */
  44980. _this.useAmbientInGrayScale = false;
  44981. /**
  44982. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44983. * The material will try to infer what glossiness each pixel should be.
  44984. */
  44985. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44986. /**
  44987. * BJS is using an harcoded light falloff based on a manually sets up range.
  44988. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44989. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44990. */
  44991. _this.usePhysicalLightFalloff = true;
  44992. /**
  44993. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44994. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44995. */
  44996. _this.useRadianceOverAlpha = true;
  44997. /**
  44998. * Allows using an object space normal map (instead of tangent space).
  44999. */
  45000. _this.useObjectSpaceNormalMap = false;
  45001. /**
  45002. * Allows using the bump map in parallax mode.
  45003. */
  45004. _this.useParallax = false;
  45005. /**
  45006. * Allows using the bump map in parallax occlusion mode.
  45007. */
  45008. _this.useParallaxOcclusion = false;
  45009. /**
  45010. * Controls the scale bias of the parallax mode.
  45011. */
  45012. _this.parallaxScaleBias = 0.05;
  45013. /**
  45014. * If sets to true, disables all the lights affecting the material.
  45015. */
  45016. _this.disableLighting = false;
  45017. /**
  45018. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45019. */
  45020. _this.forceIrradianceInFragment = false;
  45021. /**
  45022. * Number of Simultaneous lights allowed on the material.
  45023. */
  45024. _this.maxSimultaneousLights = 4;
  45025. /**
  45026. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45027. */
  45028. _this.invertNormalMapX = false;
  45029. /**
  45030. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45031. */
  45032. _this.invertNormalMapY = false;
  45033. /**
  45034. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45035. */
  45036. _this.twoSidedLighting = false;
  45037. /**
  45038. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45039. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45040. */
  45041. _this.useAlphaFresnel = false;
  45042. /**
  45043. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45044. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45045. */
  45046. _this.useLinearAlphaFresnel = false;
  45047. /**
  45048. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45049. * And/Or occlude the blended part.
  45050. */
  45051. _this.environmentBRDFTexture = null;
  45052. /**
  45053. * Force normal to face away from face.
  45054. */
  45055. _this.forceNormalForward = false;
  45056. /**
  45057. * Enables specular anti aliasing in the PBR shader.
  45058. * It will both interacts on the Geometry for analytical and IBL lighting.
  45059. * It also prefilter the roughness map based on the bump values.
  45060. */
  45061. _this.enableSpecularAntiAliasing = false;
  45062. /**
  45063. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45064. * makes the reflect vector face the model (under horizon).
  45065. */
  45066. _this.useHorizonOcclusion = true;
  45067. /**
  45068. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45069. * too much the area relying on ambient texture to define their ambient occlusion.
  45070. */
  45071. _this.useRadianceOcclusion = true;
  45072. /**
  45073. * If set to true, no lighting calculations will be applied.
  45074. */
  45075. _this.unlit = false;
  45076. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45077. return _this;
  45078. }
  45079. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45080. /**
  45081. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45082. */
  45083. get: function () {
  45084. return this._PBRMATERIAL_OPAQUE;
  45085. },
  45086. enumerable: true,
  45087. configurable: true
  45088. });
  45089. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45090. /**
  45091. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45092. */
  45093. get: function () {
  45094. return this._PBRMATERIAL_ALPHATEST;
  45095. },
  45096. enumerable: true,
  45097. configurable: true
  45098. });
  45099. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45100. /**
  45101. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45102. */
  45103. get: function () {
  45104. return this._PBRMATERIAL_ALPHABLEND;
  45105. },
  45106. enumerable: true,
  45107. configurable: true
  45108. });
  45109. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45110. /**
  45111. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45112. * They are also discarded below the alpha cutoff threshold to improve performances.
  45113. */
  45114. get: function () {
  45115. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45116. },
  45117. enumerable: true,
  45118. configurable: true
  45119. });
  45120. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45121. /**
  45122. * Gets the image processing configuration used either in this material.
  45123. */
  45124. get: function () {
  45125. return this._imageProcessingConfiguration;
  45126. },
  45127. /**
  45128. * Sets the Default image processing configuration used either in the this material.
  45129. *
  45130. * If sets to null, the scene one is in use.
  45131. */
  45132. set: function (value) {
  45133. this._attachImageProcessingConfiguration(value);
  45134. // Ensure the effect will be rebuilt.
  45135. this._markAllSubMeshesAsTexturesDirty();
  45136. },
  45137. enumerable: true,
  45138. configurable: true
  45139. });
  45140. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45141. /**
  45142. * Gets wether the color curves effect is enabled.
  45143. */
  45144. get: function () {
  45145. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45146. },
  45147. /**
  45148. * Sets wether the color curves effect is enabled.
  45149. */
  45150. set: function (value) {
  45151. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45152. },
  45153. enumerable: true,
  45154. configurable: true
  45155. });
  45156. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45157. /**
  45158. * Gets wether the color grading effect is enabled.
  45159. */
  45160. get: function () {
  45161. return this.imageProcessingConfiguration.colorGradingEnabled;
  45162. },
  45163. /**
  45164. * Gets wether the color grading effect is enabled.
  45165. */
  45166. set: function (value) {
  45167. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45168. },
  45169. enumerable: true,
  45170. configurable: true
  45171. });
  45172. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45173. /**
  45174. * Gets wether tonemapping is enabled or not.
  45175. */
  45176. get: function () {
  45177. return this._imageProcessingConfiguration.toneMappingEnabled;
  45178. },
  45179. /**
  45180. * Sets wether tonemapping is enabled or not
  45181. */
  45182. set: function (value) {
  45183. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45184. },
  45185. enumerable: true,
  45186. configurable: true
  45187. });
  45188. ;
  45189. ;
  45190. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45191. /**
  45192. * The camera exposure used on this material.
  45193. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45194. * This corresponds to a photographic exposure.
  45195. */
  45196. get: function () {
  45197. return this._imageProcessingConfiguration.exposure;
  45198. },
  45199. /**
  45200. * The camera exposure used on this material.
  45201. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45202. * This corresponds to a photographic exposure.
  45203. */
  45204. set: function (value) {
  45205. this._imageProcessingConfiguration.exposure = value;
  45206. },
  45207. enumerable: true,
  45208. configurable: true
  45209. });
  45210. ;
  45211. ;
  45212. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45213. /**
  45214. * Gets The camera contrast used on this material.
  45215. */
  45216. get: function () {
  45217. return this._imageProcessingConfiguration.contrast;
  45218. },
  45219. /**
  45220. * Sets The camera contrast used on this material.
  45221. */
  45222. set: function (value) {
  45223. this._imageProcessingConfiguration.contrast = value;
  45224. },
  45225. enumerable: true,
  45226. configurable: true
  45227. });
  45228. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45229. /**
  45230. * Gets the Color Grading 2D Lookup Texture.
  45231. */
  45232. get: function () {
  45233. return this._imageProcessingConfiguration.colorGradingTexture;
  45234. },
  45235. /**
  45236. * Sets the Color Grading 2D Lookup Texture.
  45237. */
  45238. set: function (value) {
  45239. this._imageProcessingConfiguration.colorGradingTexture = value;
  45240. },
  45241. enumerable: true,
  45242. configurable: true
  45243. });
  45244. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45245. /**
  45246. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45247. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45248. * 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;
  45249. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45250. */
  45251. get: function () {
  45252. return this._imageProcessingConfiguration.colorCurves;
  45253. },
  45254. /**
  45255. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45256. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45257. * 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;
  45258. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45259. */
  45260. set: function (value) {
  45261. this._imageProcessingConfiguration.colorCurves = value;
  45262. },
  45263. enumerable: true,
  45264. configurable: true
  45265. });
  45266. /**
  45267. * Returns the name of this material class.
  45268. */
  45269. PBRMaterial.prototype.getClassName = function () {
  45270. return "PBRMaterial";
  45271. };
  45272. /**
  45273. * Returns an array of the actively used textures.
  45274. * @returns - Array of BaseTextures
  45275. */
  45276. PBRMaterial.prototype.getActiveTextures = function () {
  45277. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45278. if (this._albedoTexture) {
  45279. activeTextures.push(this._albedoTexture);
  45280. }
  45281. if (this._ambientTexture) {
  45282. activeTextures.push(this._ambientTexture);
  45283. }
  45284. if (this._opacityTexture) {
  45285. activeTextures.push(this._opacityTexture);
  45286. }
  45287. if (this._reflectionTexture) {
  45288. activeTextures.push(this._reflectionTexture);
  45289. }
  45290. if (this._emissiveTexture) {
  45291. activeTextures.push(this._emissiveTexture);
  45292. }
  45293. if (this._reflectivityTexture) {
  45294. activeTextures.push(this._reflectivityTexture);
  45295. }
  45296. if (this._metallicTexture) {
  45297. activeTextures.push(this._metallicTexture);
  45298. }
  45299. if (this._microSurfaceTexture) {
  45300. activeTextures.push(this._microSurfaceTexture);
  45301. }
  45302. if (this._bumpTexture) {
  45303. activeTextures.push(this._bumpTexture);
  45304. }
  45305. if (this._lightmapTexture) {
  45306. activeTextures.push(this._lightmapTexture);
  45307. }
  45308. if (this._refractionTexture) {
  45309. activeTextures.push(this._refractionTexture);
  45310. }
  45311. return activeTextures;
  45312. };
  45313. /**
  45314. * Checks to see if a texture is used in the material.
  45315. * @param texture - Base texture to use.
  45316. * @returns - Boolean specifying if a texture is used in the material.
  45317. */
  45318. PBRMaterial.prototype.hasTexture = function (texture) {
  45319. if (_super.prototype.hasTexture.call(this, texture)) {
  45320. return true;
  45321. }
  45322. if (this._albedoTexture === texture) {
  45323. return true;
  45324. }
  45325. if (this._ambientTexture === texture) {
  45326. return true;
  45327. }
  45328. if (this._opacityTexture === texture) {
  45329. return true;
  45330. }
  45331. if (this._reflectionTexture === texture) {
  45332. return true;
  45333. }
  45334. if (this._reflectivityTexture === texture) {
  45335. return true;
  45336. }
  45337. if (this._metallicTexture === texture) {
  45338. return true;
  45339. }
  45340. if (this._microSurfaceTexture === texture) {
  45341. return true;
  45342. }
  45343. if (this._bumpTexture === texture) {
  45344. return true;
  45345. }
  45346. if (this._lightmapTexture === texture) {
  45347. return true;
  45348. }
  45349. if (this._refractionTexture === texture) {
  45350. return true;
  45351. }
  45352. return false;
  45353. };
  45354. /**
  45355. * Makes a duplicate of the current material.
  45356. * @param name - name to use for the new material.
  45357. */
  45358. PBRMaterial.prototype.clone = function (name) {
  45359. var _this = this;
  45360. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45361. clone.id = name;
  45362. clone.name = name;
  45363. return clone;
  45364. };
  45365. /**
  45366. * Serializes this PBR Material.
  45367. * @returns - An object with the serialized material.
  45368. */
  45369. PBRMaterial.prototype.serialize = function () {
  45370. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45371. serializationObject.customType = "BABYLON.PBRMaterial";
  45372. return serializationObject;
  45373. };
  45374. // Statics
  45375. /**
  45376. * Parses a PBR Material from a serialized object.
  45377. * @param source - Serialized object.
  45378. * @param scene - BJS scene instance.
  45379. * @param rootUrl - url for the scene object
  45380. * @returns - PBRMaterial
  45381. */
  45382. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45383. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45384. };
  45385. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45386. /**
  45387. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45388. */
  45389. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45390. /**
  45391. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45392. */
  45393. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45394. /**
  45395. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45396. * They are also discarded below the alpha cutoff threshold to improve performances.
  45397. */
  45398. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45399. __decorate([
  45400. BABYLON.serialize(),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45402. ], PBRMaterial.prototype, "directIntensity", void 0);
  45403. __decorate([
  45404. BABYLON.serialize(),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45406. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45407. __decorate([
  45408. BABYLON.serialize(),
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45410. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45411. __decorate([
  45412. BABYLON.serialize(),
  45413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45414. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45415. __decorate([
  45416. BABYLON.serialize(),
  45417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45418. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45419. __decorate([
  45420. BABYLON.serializeAsTexture(),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45422. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45423. __decorate([
  45424. BABYLON.serializeAsTexture(),
  45425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45426. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45427. __decorate([
  45428. BABYLON.serialize(),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45430. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45431. __decorate([
  45432. BABYLON.serializeAsTexture(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45434. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45435. __decorate([
  45436. BABYLON.serializeAsTexture(),
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45438. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45439. __decorate([
  45440. BABYLON.serializeAsTexture(),
  45441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45442. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45443. __decorate([
  45444. BABYLON.serializeAsTexture(),
  45445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45446. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45447. __decorate([
  45448. BABYLON.serializeAsTexture(),
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45450. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45451. __decorate([
  45452. BABYLON.serialize(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMaterial.prototype, "metallic", void 0);
  45455. __decorate([
  45456. BABYLON.serialize(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45458. ], PBRMaterial.prototype, "roughness", void 0);
  45459. __decorate([
  45460. BABYLON.serializeAsTexture(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45462. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45463. __decorate([
  45464. BABYLON.serializeAsTexture(),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45467. __decorate([
  45468. BABYLON.serializeAsTexture(),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45470. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45471. __decorate([
  45472. BABYLON.serializeAsTexture(),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45475. __decorate([
  45476. BABYLON.serializeAsColor3("ambient"),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "ambientColor", void 0);
  45479. __decorate([
  45480. BABYLON.serializeAsColor3("albedo"),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "albedoColor", void 0);
  45483. __decorate([
  45484. BABYLON.serializeAsColor3("reflectivity"),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45487. __decorate([
  45488. BABYLON.serializeAsColor3("reflection"),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45490. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45491. __decorate([
  45492. BABYLON.serializeAsColor3("emissive"),
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45494. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45495. __decorate([
  45496. BABYLON.serialize(),
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45498. ], PBRMaterial.prototype, "microSurface", void 0);
  45499. __decorate([
  45500. BABYLON.serialize(),
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45502. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45503. __decorate([
  45504. BABYLON.serialize(),
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45506. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45507. __decorate([
  45508. BABYLON.serialize(),
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45510. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45511. __decorate([
  45512. BABYLON.serialize(),
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45514. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45515. __decorate([
  45516. BABYLON.serialize(),
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45518. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45519. __decorate([
  45520. BABYLON.serialize(),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45522. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45523. __decorate([
  45524. BABYLON.serialize(),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45526. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45527. __decorate([
  45528. BABYLON.serialize(),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45530. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45531. __decorate([
  45532. BABYLON.serialize(),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45535. __decorate([
  45536. BABYLON.serialize(),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45539. __decorate([
  45540. BABYLON.serialize(),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45542. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45543. __decorate([
  45544. BABYLON.serialize(),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45546. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45547. __decorate([
  45548. BABYLON.serialize(),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45550. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45551. __decorate([
  45552. BABYLON.serialize(),
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45554. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45555. __decorate([
  45556. BABYLON.serialize(),
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45558. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45559. __decorate([
  45560. BABYLON.serialize(),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45562. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45563. __decorate([
  45564. BABYLON.serialize(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45566. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45567. __decorate([
  45568. BABYLON.serialize(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45570. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45571. __decorate([
  45572. BABYLON.serialize(),
  45573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45574. ], PBRMaterial.prototype, "useParallax", void 0);
  45575. __decorate([
  45576. BABYLON.serialize(),
  45577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45578. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45579. __decorate([
  45580. BABYLON.serialize(),
  45581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45582. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45583. __decorate([
  45584. BABYLON.serialize(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45586. ], PBRMaterial.prototype, "disableLighting", void 0);
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45594. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45603. __decorate([
  45604. BABYLON.serialize(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45607. __decorate([
  45608. BABYLON.serialize(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45611. __decorate([
  45612. BABYLON.serialize(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45615. __decorate([
  45616. BABYLON.serializeAsTexture(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45618. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45619. __decorate([
  45620. BABYLON.serialize(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45622. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45623. __decorate([
  45624. BABYLON.serialize(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45627. __decorate([
  45628. BABYLON.serialize(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45630. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45631. __decorate([
  45632. BABYLON.serialize(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45634. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45635. __decorate([
  45636. BABYLON.serialize(),
  45637. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45638. ], PBRMaterial.prototype, "unlit", void 0);
  45639. return PBRMaterial;
  45640. }(BABYLON.PBRBaseMaterial));
  45641. BABYLON.PBRMaterial = PBRMaterial;
  45642. })(BABYLON || (BABYLON = {}));
  45643. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45644. var BABYLON;
  45645. (function (BABYLON) {
  45646. /**
  45647. * The PBR material of BJS following the metal roughness convention.
  45648. *
  45649. * This fits to the PBR convention in the GLTF definition:
  45650. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45651. */
  45652. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45653. __extends(PBRMetallicRoughnessMaterial, _super);
  45654. /**
  45655. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45656. *
  45657. * @param name The material name
  45658. * @param scene The scene the material will be use in.
  45659. */
  45660. function PBRMetallicRoughnessMaterial(name, scene) {
  45661. var _this = _super.call(this, name, scene) || this;
  45662. _this._useRoughnessFromMetallicTextureAlpha = false;
  45663. _this._useRoughnessFromMetallicTextureGreen = true;
  45664. _this._useMetallnessFromMetallicTextureBlue = true;
  45665. _this.metallic = 1.0;
  45666. _this.roughness = 1.0;
  45667. return _this;
  45668. }
  45669. /**
  45670. * Return the currrent class name of the material.
  45671. */
  45672. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45673. return "PBRMetallicRoughnessMaterial";
  45674. };
  45675. /**
  45676. * Return the active textures of the material.
  45677. */
  45678. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45679. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45680. if (this.baseTexture) {
  45681. activeTextures.push(this.baseTexture);
  45682. }
  45683. if (this.metallicRoughnessTexture) {
  45684. activeTextures.push(this.metallicRoughnessTexture);
  45685. }
  45686. return activeTextures;
  45687. };
  45688. /**
  45689. * Checks to see if a texture is used in the material.
  45690. * @param texture - Base texture to use.
  45691. * @returns - Boolean specifying if a texture is used in the material.
  45692. */
  45693. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45694. if (_super.prototype.hasTexture.call(this, texture)) {
  45695. return true;
  45696. }
  45697. if (this.baseTexture === texture) {
  45698. return true;
  45699. }
  45700. if (this.metallicRoughnessTexture === texture) {
  45701. return true;
  45702. }
  45703. return false;
  45704. };
  45705. /**
  45706. * Makes a duplicate of the current material.
  45707. * @param name - name to use for the new material.
  45708. */
  45709. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45710. var _this = this;
  45711. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45712. clone.id = name;
  45713. clone.name = name;
  45714. return clone;
  45715. };
  45716. /**
  45717. * Serialize the material to a parsable JSON object.
  45718. */
  45719. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45720. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45721. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45722. return serializationObject;
  45723. };
  45724. /**
  45725. * Parses a JSON object correponding to the serialize function.
  45726. */
  45727. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45728. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45729. };
  45730. __decorate([
  45731. BABYLON.serializeAsColor3(),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45733. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45734. __decorate([
  45735. BABYLON.serializeAsTexture(),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45737. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45738. __decorate([
  45739. BABYLON.serialize(),
  45740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45741. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45742. __decorate([
  45743. BABYLON.serialize(),
  45744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45745. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45746. __decorate([
  45747. BABYLON.serializeAsTexture(),
  45748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45749. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45750. return PBRMetallicRoughnessMaterial;
  45751. }(BABYLON.PBRBaseSimpleMaterial));
  45752. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45753. })(BABYLON || (BABYLON = {}));
  45754. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45755. var BABYLON;
  45756. (function (BABYLON) {
  45757. /**
  45758. * The PBR material of BJS following the specular glossiness convention.
  45759. *
  45760. * This fits to the PBR convention in the GLTF definition:
  45761. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45762. */
  45763. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45764. __extends(PBRSpecularGlossinessMaterial, _super);
  45765. /**
  45766. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45767. *
  45768. * @param name The material name
  45769. * @param scene The scene the material will be use in.
  45770. */
  45771. function PBRSpecularGlossinessMaterial(name, scene) {
  45772. var _this = _super.call(this, name, scene) || this;
  45773. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45774. return _this;
  45775. }
  45776. /**
  45777. * Return the currrent class name of the material.
  45778. */
  45779. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45780. return "PBRSpecularGlossinessMaterial";
  45781. };
  45782. /**
  45783. * Return the active textures of the material.
  45784. */
  45785. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45786. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45787. if (this.diffuseTexture) {
  45788. activeTextures.push(this.diffuseTexture);
  45789. }
  45790. if (this.specularGlossinessTexture) {
  45791. activeTextures.push(this.specularGlossinessTexture);
  45792. }
  45793. return activeTextures;
  45794. };
  45795. /**
  45796. * Checks to see if a texture is used in the material.
  45797. * @param texture - Base texture to use.
  45798. * @returns - Boolean specifying if a texture is used in the material.
  45799. */
  45800. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45801. if (_super.prototype.hasTexture.call(this, texture)) {
  45802. return true;
  45803. }
  45804. if (this.diffuseTexture === texture) {
  45805. return true;
  45806. }
  45807. if (this.specularGlossinessTexture === texture) {
  45808. return true;
  45809. }
  45810. return false;
  45811. };
  45812. /**
  45813. * Makes a duplicate of the current material.
  45814. * @param name - name to use for the new material.
  45815. */
  45816. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45817. var _this = this;
  45818. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45819. clone.id = name;
  45820. clone.name = name;
  45821. return clone;
  45822. };
  45823. /**
  45824. * Serialize the material to a parsable JSON object.
  45825. */
  45826. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45827. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45828. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45829. return serializationObject;
  45830. };
  45831. /**
  45832. * Parses a JSON object correponding to the serialize function.
  45833. */
  45834. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45835. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45836. };
  45837. __decorate([
  45838. BABYLON.serializeAsColor3("diffuse"),
  45839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45840. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45841. __decorate([
  45842. BABYLON.serializeAsTexture(),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45844. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45845. __decorate([
  45846. BABYLON.serializeAsColor3("specular"),
  45847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45848. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45849. __decorate([
  45850. BABYLON.serialize(),
  45851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45852. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45853. __decorate([
  45854. BABYLON.serializeAsTexture(),
  45855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45856. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45857. return PBRSpecularGlossinessMaterial;
  45858. }(BABYLON.PBRBaseSimpleMaterial));
  45859. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45860. })(BABYLON || (BABYLON = {}));
  45861. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45862. var BABYLON;
  45863. (function (BABYLON) {
  45864. BABYLON.CameraInputTypes = {};
  45865. var CameraInputsManager = /** @class */ (function () {
  45866. function CameraInputsManager(camera) {
  45867. this.attached = {};
  45868. this.camera = camera;
  45869. this.checkInputs = function () { };
  45870. }
  45871. /**
  45872. * Add an input method to a camera.
  45873. * builtin inputs example: camera.inputs.addGamepad();
  45874. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45875. * @param input camera input method
  45876. */
  45877. CameraInputsManager.prototype.add = function (input) {
  45878. var type = input.getSimpleName();
  45879. if (this.attached[type]) {
  45880. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45881. return;
  45882. }
  45883. this.attached[type] = input;
  45884. input.camera = this.camera;
  45885. //for checkInputs, we are dynamically creating a function
  45886. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45887. if (input.checkInputs) {
  45888. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45889. }
  45890. if (this.attachedElement) {
  45891. input.attachControl(this.attachedElement);
  45892. }
  45893. };
  45894. /**
  45895. * Remove a specific input method from a camera
  45896. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45897. * @param inputToRemove camera input method
  45898. */
  45899. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45900. for (var cam in this.attached) {
  45901. var input = this.attached[cam];
  45902. if (input === inputToRemove) {
  45903. input.detachControl(this.attachedElement);
  45904. input.camera = null;
  45905. delete this.attached[cam];
  45906. this.rebuildInputCheck();
  45907. }
  45908. }
  45909. };
  45910. CameraInputsManager.prototype.removeByType = function (inputType) {
  45911. for (var cam in this.attached) {
  45912. var input = this.attached[cam];
  45913. if (input.getClassName() === inputType) {
  45914. input.detachControl(this.attachedElement);
  45915. input.camera = null;
  45916. delete this.attached[cam];
  45917. this.rebuildInputCheck();
  45918. }
  45919. }
  45920. };
  45921. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45922. var current = this.checkInputs;
  45923. return function () {
  45924. current();
  45925. fn();
  45926. };
  45927. };
  45928. CameraInputsManager.prototype.attachInput = function (input) {
  45929. if (this.attachedElement) {
  45930. input.attachControl(this.attachedElement, this.noPreventDefault);
  45931. }
  45932. };
  45933. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45934. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45935. if (this.attachedElement) {
  45936. return;
  45937. }
  45938. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45939. this.attachedElement = element;
  45940. this.noPreventDefault = noPreventDefault;
  45941. for (var cam in this.attached) {
  45942. this.attached[cam].attachControl(element, noPreventDefault);
  45943. }
  45944. };
  45945. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45946. if (disconnect === void 0) { disconnect = false; }
  45947. if (this.attachedElement !== element) {
  45948. return;
  45949. }
  45950. for (var cam in this.attached) {
  45951. this.attached[cam].detachControl(element);
  45952. if (disconnect) {
  45953. this.attached[cam].camera = null;
  45954. }
  45955. }
  45956. this.attachedElement = null;
  45957. };
  45958. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45959. this.checkInputs = function () { };
  45960. for (var cam in this.attached) {
  45961. var input = this.attached[cam];
  45962. if (input.checkInputs) {
  45963. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45964. }
  45965. }
  45966. };
  45967. /**
  45968. * Remove all attached input methods from a camera
  45969. */
  45970. CameraInputsManager.prototype.clear = function () {
  45971. if (this.attachedElement) {
  45972. this.detachElement(this.attachedElement, true);
  45973. }
  45974. this.attached = {};
  45975. this.attachedElement = null;
  45976. this.checkInputs = function () { };
  45977. };
  45978. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45979. var inputs = {};
  45980. for (var cam in this.attached) {
  45981. var input = this.attached[cam];
  45982. var res = BABYLON.SerializationHelper.Serialize(input);
  45983. inputs[input.getClassName()] = res;
  45984. }
  45985. serializedCamera.inputsmgr = inputs;
  45986. };
  45987. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45988. var parsedInputs = parsedCamera.inputsmgr;
  45989. if (parsedInputs) {
  45990. this.clear();
  45991. for (var n in parsedInputs) {
  45992. var construct = BABYLON.CameraInputTypes[n];
  45993. if (construct) {
  45994. var parsedinput = parsedInputs[n];
  45995. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45996. this.add(input);
  45997. }
  45998. }
  45999. }
  46000. else {
  46001. //2016-03-08 this part is for managing backward compatibility
  46002. for (var n in this.attached) {
  46003. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46004. if (construct) {
  46005. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46006. this.remove(this.attached[n]);
  46007. this.add(input);
  46008. }
  46009. }
  46010. }
  46011. };
  46012. return CameraInputsManager;
  46013. }());
  46014. BABYLON.CameraInputsManager = CameraInputsManager;
  46015. })(BABYLON || (BABYLON = {}));
  46016. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46017. var BABYLON;
  46018. (function (BABYLON) {
  46019. var TargetCamera = /** @class */ (function (_super) {
  46020. __extends(TargetCamera, _super);
  46021. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46022. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46023. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46024. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46025. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46026. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46027. _this.speed = 2.0;
  46028. _this.noRotationConstraint = false;
  46029. _this.lockedTarget = null;
  46030. _this._currentTarget = BABYLON.Vector3.Zero();
  46031. _this._viewMatrix = BABYLON.Matrix.Zero();
  46032. _this._camMatrix = BABYLON.Matrix.Zero();
  46033. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46034. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46035. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46036. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46037. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46038. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46039. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46040. return _this;
  46041. }
  46042. TargetCamera.prototype.getFrontPosition = function (distance) {
  46043. this.getWorldMatrix();
  46044. var direction = this.getTarget().subtract(this.position);
  46045. direction.normalize();
  46046. direction.scaleInPlace(distance);
  46047. return this.globalPosition.add(direction);
  46048. };
  46049. TargetCamera.prototype._getLockedTargetPosition = function () {
  46050. if (!this.lockedTarget) {
  46051. return null;
  46052. }
  46053. if (this.lockedTarget.absolutePosition) {
  46054. this.lockedTarget.computeWorldMatrix();
  46055. }
  46056. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46057. };
  46058. TargetCamera.prototype.storeState = function () {
  46059. this._storedPosition = this.position.clone();
  46060. this._storedRotation = this.rotation.clone();
  46061. if (this.rotationQuaternion) {
  46062. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46063. }
  46064. return _super.prototype.storeState.call(this);
  46065. };
  46066. /**
  46067. * Restored camera state. You must call storeState() first
  46068. */
  46069. TargetCamera.prototype._restoreStateValues = function () {
  46070. if (!_super.prototype._restoreStateValues.call(this)) {
  46071. return false;
  46072. }
  46073. this.position = this._storedPosition.clone();
  46074. this.rotation = this._storedRotation.clone();
  46075. if (this.rotationQuaternion) {
  46076. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46077. }
  46078. this.cameraDirection.copyFromFloats(0, 0, 0);
  46079. this.cameraRotation.copyFromFloats(0, 0);
  46080. return true;
  46081. };
  46082. // Cache
  46083. TargetCamera.prototype._initCache = function () {
  46084. _super.prototype._initCache.call(this);
  46085. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46086. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46087. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46088. };
  46089. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46090. if (!ignoreParentClass) {
  46091. _super.prototype._updateCache.call(this);
  46092. }
  46093. var lockedTargetPosition = this._getLockedTargetPosition();
  46094. if (!lockedTargetPosition) {
  46095. this._cache.lockedTarget = null;
  46096. }
  46097. else {
  46098. if (!this._cache.lockedTarget) {
  46099. this._cache.lockedTarget = lockedTargetPosition.clone();
  46100. }
  46101. else {
  46102. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46103. }
  46104. }
  46105. this._cache.rotation.copyFrom(this.rotation);
  46106. if (this.rotationQuaternion)
  46107. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46108. };
  46109. // Synchronized
  46110. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46111. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46112. return false;
  46113. }
  46114. var lockedTargetPosition = this._getLockedTargetPosition();
  46115. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46116. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46117. };
  46118. // Methods
  46119. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46120. var engine = this.getEngine();
  46121. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46122. };
  46123. // Target
  46124. TargetCamera.prototype.setTarget = function (target) {
  46125. this.upVector.normalize();
  46126. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46127. this._camMatrix.invert();
  46128. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46129. var vDir = target.subtract(this.position);
  46130. if (vDir.x >= 0.0) {
  46131. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46132. }
  46133. else {
  46134. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46135. }
  46136. this.rotation.z = 0;
  46137. if (isNaN(this.rotation.x)) {
  46138. this.rotation.x = 0;
  46139. }
  46140. if (isNaN(this.rotation.y)) {
  46141. this.rotation.y = 0;
  46142. }
  46143. if (isNaN(this.rotation.z)) {
  46144. this.rotation.z = 0;
  46145. }
  46146. if (this.rotationQuaternion) {
  46147. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46148. }
  46149. };
  46150. /**
  46151. * Return the current target position of the camera. This value is expressed in local space.
  46152. */
  46153. TargetCamera.prototype.getTarget = function () {
  46154. return this._currentTarget;
  46155. };
  46156. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46157. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46158. };
  46159. TargetCamera.prototype._updatePosition = function () {
  46160. if (this.parent) {
  46161. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46162. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46163. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46164. return;
  46165. }
  46166. this.position.addInPlace(this.cameraDirection);
  46167. };
  46168. TargetCamera.prototype._checkInputs = function () {
  46169. var needToMove = this._decideIfNeedsToMove();
  46170. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46171. // Move
  46172. if (needToMove) {
  46173. this._updatePosition();
  46174. }
  46175. // Rotate
  46176. if (needToRotate) {
  46177. this.rotation.x += this.cameraRotation.x;
  46178. this.rotation.y += this.cameraRotation.y;
  46179. //rotate, if quaternion is set and rotation was used
  46180. if (this.rotationQuaternion) {
  46181. var len = this.rotation.lengthSquared();
  46182. if (len) {
  46183. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46184. }
  46185. }
  46186. if (!this.noRotationConstraint) {
  46187. var limit = (Math.PI / 2) * 0.95;
  46188. if (this.rotation.x > limit)
  46189. this.rotation.x = limit;
  46190. if (this.rotation.x < -limit)
  46191. this.rotation.x = -limit;
  46192. }
  46193. }
  46194. // Inertia
  46195. if (needToMove) {
  46196. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46197. this.cameraDirection.x = 0;
  46198. }
  46199. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46200. this.cameraDirection.y = 0;
  46201. }
  46202. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46203. this.cameraDirection.z = 0;
  46204. }
  46205. this.cameraDirection.scaleInPlace(this.inertia);
  46206. }
  46207. if (needToRotate) {
  46208. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46209. this.cameraRotation.x = 0;
  46210. }
  46211. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46212. this.cameraRotation.y = 0;
  46213. }
  46214. this.cameraRotation.scaleInPlace(this.inertia);
  46215. }
  46216. _super.prototype._checkInputs.call(this);
  46217. };
  46218. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46219. if (this.rotationQuaternion) {
  46220. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46221. }
  46222. else {
  46223. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46224. }
  46225. //update the up vector!
  46226. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46227. };
  46228. TargetCamera.prototype._getViewMatrix = function () {
  46229. if (this.lockedTarget) {
  46230. this.setTarget(this._getLockedTargetPosition());
  46231. }
  46232. // Compute
  46233. this._updateCameraRotationMatrix();
  46234. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46235. // Computing target and final matrix
  46236. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46237. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46238. return this._viewMatrix;
  46239. };
  46240. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46241. if (this.parent) {
  46242. var parentWorldMatrix = this.parent.getWorldMatrix();
  46243. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46244. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46245. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46246. this._markSyncedWithParent();
  46247. }
  46248. else {
  46249. this._globalPosition.copyFrom(this.position);
  46250. this._globalCurrentTarget.copyFrom(target);
  46251. this._globalCurrentUpVector.copyFrom(up);
  46252. }
  46253. if (this.getScene().useRightHandedSystem) {
  46254. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46255. }
  46256. else {
  46257. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46258. }
  46259. };
  46260. /**
  46261. * @override
  46262. * Override Camera.createRigCamera
  46263. */
  46264. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46265. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46266. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46267. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46268. if (!this.rotationQuaternion) {
  46269. this.rotationQuaternion = new BABYLON.Quaternion();
  46270. }
  46271. rigCamera._cameraRigParams = {};
  46272. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46273. }
  46274. return rigCamera;
  46275. }
  46276. return null;
  46277. };
  46278. /**
  46279. * @override
  46280. * Override Camera._updateRigCameras
  46281. */
  46282. TargetCamera.prototype._updateRigCameras = function () {
  46283. var camLeft = this._rigCameras[0];
  46284. var camRight = this._rigCameras[1];
  46285. switch (this.cameraRigMode) {
  46286. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46287. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46288. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46289. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46290. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46291. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46292. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46293. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46294. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46295. camLeft.setTarget(this.getTarget());
  46296. camRight.setTarget(this.getTarget());
  46297. break;
  46298. case BABYLON.Camera.RIG_MODE_VR:
  46299. if (camLeft.rotationQuaternion) {
  46300. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46301. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46302. }
  46303. else {
  46304. camLeft.rotation.copyFrom(this.rotation);
  46305. camRight.rotation.copyFrom(this.rotation);
  46306. }
  46307. camLeft.position.copyFrom(this.position);
  46308. camRight.position.copyFrom(this.position);
  46309. break;
  46310. }
  46311. _super.prototype._updateRigCameras.call(this);
  46312. };
  46313. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46314. if (!this._rigCamTransformMatrix) {
  46315. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46316. }
  46317. var target = this.getTarget();
  46318. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46319. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46320. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46321. };
  46322. TargetCamera.prototype.getClassName = function () {
  46323. return "TargetCamera";
  46324. };
  46325. __decorate([
  46326. BABYLON.serializeAsVector3()
  46327. ], TargetCamera.prototype, "rotation", void 0);
  46328. __decorate([
  46329. BABYLON.serialize()
  46330. ], TargetCamera.prototype, "speed", void 0);
  46331. __decorate([
  46332. BABYLON.serializeAsMeshReference("lockedTargetId")
  46333. ], TargetCamera.prototype, "lockedTarget", void 0);
  46334. return TargetCamera;
  46335. }(BABYLON.Camera));
  46336. BABYLON.TargetCamera = TargetCamera;
  46337. })(BABYLON || (BABYLON = {}));
  46338. //# sourceMappingURL=babylon.targetCamera.js.map
  46339. var BABYLON;
  46340. (function (BABYLON) {
  46341. var FreeCameraMouseInput = /** @class */ (function () {
  46342. function FreeCameraMouseInput(touchEnabled) {
  46343. if (touchEnabled === void 0) { touchEnabled = true; }
  46344. this.touchEnabled = touchEnabled;
  46345. this.buttons = [0, 1, 2];
  46346. this.angularSensibility = 2000.0;
  46347. this.previousPosition = null;
  46348. }
  46349. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46350. var _this = this;
  46351. var engine = this.camera.getEngine();
  46352. if (!this._pointerInput) {
  46353. this._pointerInput = function (p, s) {
  46354. var evt = p.event;
  46355. if (engine.isInVRExclusivePointerMode) {
  46356. return;
  46357. }
  46358. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46359. return;
  46360. }
  46361. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46362. return;
  46363. }
  46364. var srcElement = (evt.srcElement || evt.target);
  46365. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46366. try {
  46367. srcElement.setPointerCapture(evt.pointerId);
  46368. }
  46369. catch (e) {
  46370. //Nothing to do with the error. Execution will continue.
  46371. }
  46372. _this.previousPosition = {
  46373. x: evt.clientX,
  46374. y: evt.clientY
  46375. };
  46376. if (!noPreventDefault) {
  46377. evt.preventDefault();
  46378. element.focus();
  46379. }
  46380. }
  46381. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46382. try {
  46383. srcElement.releasePointerCapture(evt.pointerId);
  46384. }
  46385. catch (e) {
  46386. //Nothing to do with the error.
  46387. }
  46388. _this.previousPosition = null;
  46389. if (!noPreventDefault) {
  46390. evt.preventDefault();
  46391. }
  46392. }
  46393. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46394. if (!_this.previousPosition || engine.isPointerLock) {
  46395. return;
  46396. }
  46397. var offsetX = evt.clientX - _this.previousPosition.x;
  46398. if (_this.camera.getScene().useRightHandedSystem)
  46399. offsetX *= -1;
  46400. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46401. offsetX *= -1;
  46402. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46403. var offsetY = evt.clientY - _this.previousPosition.y;
  46404. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46405. _this.previousPosition = {
  46406. x: evt.clientX,
  46407. y: evt.clientY
  46408. };
  46409. if (!noPreventDefault) {
  46410. evt.preventDefault();
  46411. }
  46412. }
  46413. };
  46414. }
  46415. this._onMouseMove = function (evt) {
  46416. if (!engine.isPointerLock) {
  46417. return;
  46418. }
  46419. if (engine.isInVRExclusivePointerMode) {
  46420. return;
  46421. }
  46422. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46423. if (_this.camera.getScene().useRightHandedSystem)
  46424. offsetX *= -1;
  46425. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46426. offsetX *= -1;
  46427. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46428. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46429. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46430. _this.previousPosition = null;
  46431. if (!noPreventDefault) {
  46432. evt.preventDefault();
  46433. }
  46434. };
  46435. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46436. element.addEventListener("mousemove", this._onMouseMove, false);
  46437. };
  46438. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46439. if (this._observer && element) {
  46440. this.camera.getScene().onPointerObservable.remove(this._observer);
  46441. if (this._onMouseMove) {
  46442. element.removeEventListener("mousemove", this._onMouseMove);
  46443. }
  46444. this._observer = null;
  46445. this._onMouseMove = null;
  46446. this.previousPosition = null;
  46447. }
  46448. };
  46449. FreeCameraMouseInput.prototype.getClassName = function () {
  46450. return "FreeCameraMouseInput";
  46451. };
  46452. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46453. return "mouse";
  46454. };
  46455. __decorate([
  46456. BABYLON.serialize()
  46457. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46458. __decorate([
  46459. BABYLON.serialize()
  46460. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46461. return FreeCameraMouseInput;
  46462. }());
  46463. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46464. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46465. })(BABYLON || (BABYLON = {}));
  46466. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46467. var BABYLON;
  46468. (function (BABYLON) {
  46469. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46470. function FreeCameraKeyboardMoveInput() {
  46471. this._keys = new Array();
  46472. this.keysUp = [38];
  46473. this.keysDown = [40];
  46474. this.keysLeft = [37];
  46475. this.keysRight = [39];
  46476. }
  46477. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46478. var _this = this;
  46479. if (this._onCanvasBlurObserver) {
  46480. return;
  46481. }
  46482. this._scene = this.camera.getScene();
  46483. this._engine = this._scene.getEngine();
  46484. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46485. _this._keys = [];
  46486. });
  46487. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46488. var evt = info.event;
  46489. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46490. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46491. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46492. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46493. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46494. var index = _this._keys.indexOf(evt.keyCode);
  46495. if (index === -1) {
  46496. _this._keys.push(evt.keyCode);
  46497. }
  46498. if (!noPreventDefault) {
  46499. evt.preventDefault();
  46500. }
  46501. }
  46502. }
  46503. else {
  46504. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46505. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46506. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46507. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46508. var index = _this._keys.indexOf(evt.keyCode);
  46509. if (index >= 0) {
  46510. _this._keys.splice(index, 1);
  46511. }
  46512. if (!noPreventDefault) {
  46513. evt.preventDefault();
  46514. }
  46515. }
  46516. }
  46517. });
  46518. };
  46519. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46520. if (this._scene) {
  46521. if (this._onKeyboardObserver) {
  46522. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46523. }
  46524. if (this._onCanvasBlurObserver) {
  46525. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46526. }
  46527. this._onKeyboardObserver = null;
  46528. this._onCanvasBlurObserver = null;
  46529. }
  46530. this._keys = [];
  46531. };
  46532. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46533. if (this._onKeyboardObserver) {
  46534. var camera = this.camera;
  46535. // Keyboard
  46536. for (var index = 0; index < this._keys.length; index++) {
  46537. var keyCode = this._keys[index];
  46538. var speed = camera._computeLocalCameraSpeed();
  46539. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46540. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46541. }
  46542. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46543. camera._localDirection.copyFromFloats(0, 0, speed);
  46544. }
  46545. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46546. camera._localDirection.copyFromFloats(speed, 0, 0);
  46547. }
  46548. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46549. camera._localDirection.copyFromFloats(0, 0, -speed);
  46550. }
  46551. if (camera.getScene().useRightHandedSystem) {
  46552. camera._localDirection.z *= -1;
  46553. }
  46554. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46555. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46556. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46557. }
  46558. }
  46559. };
  46560. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46561. return "FreeCameraKeyboardMoveInput";
  46562. };
  46563. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46564. this._keys = [];
  46565. };
  46566. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46567. return "keyboard";
  46568. };
  46569. __decorate([
  46570. BABYLON.serialize()
  46571. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46572. __decorate([
  46573. BABYLON.serialize()
  46574. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46575. __decorate([
  46576. BABYLON.serialize()
  46577. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46578. __decorate([
  46579. BABYLON.serialize()
  46580. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46581. return FreeCameraKeyboardMoveInput;
  46582. }());
  46583. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46584. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46585. })(BABYLON || (BABYLON = {}));
  46586. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46587. var BABYLON;
  46588. (function (BABYLON) {
  46589. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46590. __extends(FreeCameraInputsManager, _super);
  46591. function FreeCameraInputsManager(camera) {
  46592. return _super.call(this, camera) || this;
  46593. }
  46594. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46595. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46596. return this;
  46597. };
  46598. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46599. if (touchEnabled === void 0) { touchEnabled = true; }
  46600. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46601. return this;
  46602. };
  46603. FreeCameraInputsManager.prototype.addGamepad = function () {
  46604. this.add(new BABYLON.FreeCameraGamepadInput());
  46605. return this;
  46606. };
  46607. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46608. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46609. return this;
  46610. };
  46611. FreeCameraInputsManager.prototype.addTouch = function () {
  46612. this.add(new BABYLON.FreeCameraTouchInput());
  46613. return this;
  46614. };
  46615. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46616. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46617. return this;
  46618. };
  46619. return FreeCameraInputsManager;
  46620. }(BABYLON.CameraInputsManager));
  46621. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46622. })(BABYLON || (BABYLON = {}));
  46623. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46624. var BABYLON;
  46625. (function (BABYLON) {
  46626. var FreeCamera = /** @class */ (function (_super) {
  46627. __extends(FreeCamera, _super);
  46628. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46629. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46630. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46631. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46632. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46633. _this.checkCollisions = false;
  46634. _this.applyGravity = false;
  46635. _this._needMoveForGravity = false;
  46636. _this._oldPosition = BABYLON.Vector3.Zero();
  46637. _this._diffPosition = BABYLON.Vector3.Zero();
  46638. _this._newPosition = BABYLON.Vector3.Zero();
  46639. // Collisions
  46640. _this._collisionMask = -1;
  46641. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46642. if (collidedMesh === void 0) { collidedMesh = null; }
  46643. //TODO move this to the collision coordinator!
  46644. if (_this.getScene().workerCollisions)
  46645. newPosition.multiplyInPlace(_this._collider._radius);
  46646. var updatePosition = function (newPos) {
  46647. _this._newPosition.copyFrom(newPos);
  46648. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46649. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46650. _this.position.addInPlace(_this._diffPosition);
  46651. if (_this.onCollide && collidedMesh) {
  46652. _this.onCollide(collidedMesh);
  46653. }
  46654. }
  46655. };
  46656. updatePosition(newPosition);
  46657. };
  46658. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46659. _this.inputs.addKeyboard().addMouse();
  46660. return _this;
  46661. }
  46662. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46663. //-- begin properties for backward compatibility for inputs
  46664. /**
  46665. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46666. * Higher values reduce sensitivity.
  46667. */
  46668. get: function () {
  46669. var mouse = this.inputs.attached["mouse"];
  46670. if (mouse)
  46671. return mouse.angularSensibility;
  46672. return 0;
  46673. },
  46674. /**
  46675. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46676. * Higher values reduce sensitivity.
  46677. */
  46678. set: function (value) {
  46679. var mouse = this.inputs.attached["mouse"];
  46680. if (mouse)
  46681. mouse.angularSensibility = value;
  46682. },
  46683. enumerable: true,
  46684. configurable: true
  46685. });
  46686. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46687. get: function () {
  46688. var keyboard = this.inputs.attached["keyboard"];
  46689. if (keyboard)
  46690. return keyboard.keysUp;
  46691. return [];
  46692. },
  46693. set: function (value) {
  46694. var keyboard = this.inputs.attached["keyboard"];
  46695. if (keyboard)
  46696. keyboard.keysUp = value;
  46697. },
  46698. enumerable: true,
  46699. configurable: true
  46700. });
  46701. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46702. get: function () {
  46703. var keyboard = this.inputs.attached["keyboard"];
  46704. if (keyboard)
  46705. return keyboard.keysDown;
  46706. return [];
  46707. },
  46708. set: function (value) {
  46709. var keyboard = this.inputs.attached["keyboard"];
  46710. if (keyboard)
  46711. keyboard.keysDown = value;
  46712. },
  46713. enumerable: true,
  46714. configurable: true
  46715. });
  46716. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46717. get: function () {
  46718. var keyboard = this.inputs.attached["keyboard"];
  46719. if (keyboard)
  46720. return keyboard.keysLeft;
  46721. return [];
  46722. },
  46723. set: function (value) {
  46724. var keyboard = this.inputs.attached["keyboard"];
  46725. if (keyboard)
  46726. keyboard.keysLeft = value;
  46727. },
  46728. enumerable: true,
  46729. configurable: true
  46730. });
  46731. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46732. get: function () {
  46733. var keyboard = this.inputs.attached["keyboard"];
  46734. if (keyboard)
  46735. return keyboard.keysRight;
  46736. return [];
  46737. },
  46738. set: function (value) {
  46739. var keyboard = this.inputs.attached["keyboard"];
  46740. if (keyboard)
  46741. keyboard.keysRight = value;
  46742. },
  46743. enumerable: true,
  46744. configurable: true
  46745. });
  46746. // Controls
  46747. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46748. this.inputs.attachElement(element, noPreventDefault);
  46749. };
  46750. FreeCamera.prototype.detachControl = function (element) {
  46751. this.inputs.detachElement(element);
  46752. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46753. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46754. };
  46755. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46756. get: function () {
  46757. return this._collisionMask;
  46758. },
  46759. set: function (mask) {
  46760. this._collisionMask = !isNaN(mask) ? mask : -1;
  46761. },
  46762. enumerable: true,
  46763. configurable: true
  46764. });
  46765. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46766. var globalPosition;
  46767. if (this.parent) {
  46768. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46769. }
  46770. else {
  46771. globalPosition = this.position;
  46772. }
  46773. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46774. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46775. if (!this._collider) {
  46776. this._collider = new BABYLON.Collider();
  46777. }
  46778. this._collider._radius = this.ellipsoid;
  46779. this._collider.collisionMask = this._collisionMask;
  46780. //no need for clone, as long as gravity is not on.
  46781. var actualDisplacement = displacement;
  46782. //add gravity to the direction to prevent the dual-collision checking
  46783. if (this.applyGravity) {
  46784. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46785. actualDisplacement = displacement.add(this.getScene().gravity);
  46786. }
  46787. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46788. };
  46789. FreeCamera.prototype._checkInputs = function () {
  46790. if (!this._localDirection) {
  46791. this._localDirection = BABYLON.Vector3.Zero();
  46792. this._transformedDirection = BABYLON.Vector3.Zero();
  46793. }
  46794. this.inputs.checkInputs();
  46795. _super.prototype._checkInputs.call(this);
  46796. };
  46797. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46798. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46799. };
  46800. FreeCamera.prototype._updatePosition = function () {
  46801. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46802. this._collideWithWorld(this.cameraDirection);
  46803. }
  46804. else {
  46805. _super.prototype._updatePosition.call(this);
  46806. }
  46807. };
  46808. FreeCamera.prototype.dispose = function () {
  46809. this.inputs.clear();
  46810. _super.prototype.dispose.call(this);
  46811. };
  46812. FreeCamera.prototype.getClassName = function () {
  46813. return "FreeCamera";
  46814. };
  46815. __decorate([
  46816. BABYLON.serializeAsVector3()
  46817. ], FreeCamera.prototype, "ellipsoid", void 0);
  46818. __decorate([
  46819. BABYLON.serializeAsVector3()
  46820. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46821. __decorate([
  46822. BABYLON.serialize()
  46823. ], FreeCamera.prototype, "checkCollisions", void 0);
  46824. __decorate([
  46825. BABYLON.serialize()
  46826. ], FreeCamera.prototype, "applyGravity", void 0);
  46827. return FreeCamera;
  46828. }(BABYLON.TargetCamera));
  46829. BABYLON.FreeCamera = FreeCamera;
  46830. })(BABYLON || (BABYLON = {}));
  46831. //# sourceMappingURL=babylon.freeCamera.js.map
  46832. var BABYLON;
  46833. (function (BABYLON) {
  46834. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46835. function ArcRotateCameraKeyboardMoveInput() {
  46836. this._keys = new Array();
  46837. this.keysUp = [38];
  46838. this.keysDown = [40];
  46839. this.keysLeft = [37];
  46840. this.keysRight = [39];
  46841. this.keysReset = [220];
  46842. this.panningSensibility = 50.0;
  46843. this.zoomingSensibility = 25.0;
  46844. this.useAltToZoom = true;
  46845. }
  46846. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46847. var _this = this;
  46848. if (this._onCanvasBlurObserver) {
  46849. return;
  46850. }
  46851. this._scene = this.camera.getScene();
  46852. this._engine = this._scene.getEngine();
  46853. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46854. _this._keys = [];
  46855. });
  46856. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46857. var evt = info.event;
  46858. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46859. _this._ctrlPressed = evt.ctrlKey;
  46860. _this._altPressed = evt.altKey;
  46861. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46862. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46863. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46864. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46865. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46866. var index = _this._keys.indexOf(evt.keyCode);
  46867. if (index === -1) {
  46868. _this._keys.push(evt.keyCode);
  46869. }
  46870. if (evt.preventDefault) {
  46871. if (!noPreventDefault) {
  46872. evt.preventDefault();
  46873. }
  46874. }
  46875. }
  46876. }
  46877. else {
  46878. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46879. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46880. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46881. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46882. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46883. var index = _this._keys.indexOf(evt.keyCode);
  46884. if (index >= 0) {
  46885. _this._keys.splice(index, 1);
  46886. }
  46887. if (evt.preventDefault) {
  46888. if (!noPreventDefault) {
  46889. evt.preventDefault();
  46890. }
  46891. }
  46892. }
  46893. }
  46894. });
  46895. };
  46896. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46897. if (this._scene) {
  46898. if (this._onKeyboardObserver) {
  46899. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46900. }
  46901. if (this._onCanvasBlurObserver) {
  46902. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46903. }
  46904. this._onKeyboardObserver = null;
  46905. this._onCanvasBlurObserver = null;
  46906. }
  46907. this._keys = [];
  46908. };
  46909. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46910. if (this._onKeyboardObserver) {
  46911. var camera = this.camera;
  46912. for (var index = 0; index < this._keys.length; index++) {
  46913. var keyCode = this._keys[index];
  46914. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46915. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46916. camera.inertialPanningX -= 1 / this.panningSensibility;
  46917. }
  46918. else {
  46919. camera.inertialAlphaOffset -= 0.01;
  46920. }
  46921. }
  46922. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46923. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46924. camera.inertialPanningY += 1 / this.panningSensibility;
  46925. }
  46926. else if (this._altPressed && this.useAltToZoom) {
  46927. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46928. }
  46929. else {
  46930. camera.inertialBetaOffset -= 0.01;
  46931. }
  46932. }
  46933. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46934. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46935. camera.inertialPanningX += 1 / this.panningSensibility;
  46936. }
  46937. else {
  46938. camera.inertialAlphaOffset += 0.01;
  46939. }
  46940. }
  46941. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46942. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46943. camera.inertialPanningY -= 1 / this.panningSensibility;
  46944. }
  46945. else if (this._altPressed && this.useAltToZoom) {
  46946. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46947. }
  46948. else {
  46949. camera.inertialBetaOffset += 0.01;
  46950. }
  46951. }
  46952. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46953. camera.restoreState();
  46954. }
  46955. }
  46956. }
  46957. };
  46958. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46959. return "ArcRotateCameraKeyboardMoveInput";
  46960. };
  46961. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46962. return "keyboard";
  46963. };
  46964. __decorate([
  46965. BABYLON.serialize()
  46966. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46967. __decorate([
  46968. BABYLON.serialize()
  46969. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46970. __decorate([
  46971. BABYLON.serialize()
  46972. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46973. __decorate([
  46974. BABYLON.serialize()
  46975. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46976. __decorate([
  46977. BABYLON.serialize()
  46978. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46979. __decorate([
  46980. BABYLON.serialize()
  46981. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46982. __decorate([
  46983. BABYLON.serialize()
  46984. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46985. __decorate([
  46986. BABYLON.serialize()
  46987. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46988. return ArcRotateCameraKeyboardMoveInput;
  46989. }());
  46990. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46991. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46992. })(BABYLON || (BABYLON = {}));
  46993. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46994. var BABYLON;
  46995. (function (BABYLON) {
  46996. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46997. function ArcRotateCameraMouseWheelInput() {
  46998. this.wheelPrecision = 3.0;
  46999. /**
  47000. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47001. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47002. */
  47003. this.wheelDeltaPercentage = 0;
  47004. }
  47005. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47006. var _this = this;
  47007. this._wheel = function (p, s) {
  47008. //sanity check - this should be a PointerWheel event.
  47009. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47010. return;
  47011. var event = p.event;
  47012. var delta = 0;
  47013. if (event.wheelDelta) {
  47014. if (_this.wheelDeltaPercentage) {
  47015. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47016. if (event.wheelDelta > 0) {
  47017. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47018. }
  47019. else {
  47020. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47021. }
  47022. }
  47023. else {
  47024. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47025. }
  47026. }
  47027. else if (event.detail) {
  47028. delta = -event.detail / _this.wheelPrecision;
  47029. }
  47030. if (delta)
  47031. _this.camera.inertialRadiusOffset += delta;
  47032. if (event.preventDefault) {
  47033. if (!noPreventDefault) {
  47034. event.preventDefault();
  47035. }
  47036. }
  47037. };
  47038. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47039. };
  47040. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47041. if (this._observer && element) {
  47042. this.camera.getScene().onPointerObservable.remove(this._observer);
  47043. this._observer = null;
  47044. this._wheel = null;
  47045. }
  47046. };
  47047. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47048. return "ArcRotateCameraMouseWheelInput";
  47049. };
  47050. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47051. return "mousewheel";
  47052. };
  47053. __decorate([
  47054. BABYLON.serialize()
  47055. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47056. __decorate([
  47057. BABYLON.serialize()
  47058. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47059. return ArcRotateCameraMouseWheelInput;
  47060. }());
  47061. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47062. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47063. })(BABYLON || (BABYLON = {}));
  47064. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47065. var BABYLON;
  47066. (function (BABYLON) {
  47067. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47068. function ArcRotateCameraPointersInput() {
  47069. this.buttons = [0, 1, 2];
  47070. this.angularSensibilityX = 1000.0;
  47071. this.angularSensibilityY = 1000.0;
  47072. this.pinchPrecision = 12.0;
  47073. /**
  47074. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47075. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47076. */
  47077. this.pinchDeltaPercentage = 0;
  47078. this.panningSensibility = 1000.0;
  47079. this.multiTouchPanning = true;
  47080. this.multiTouchPanAndZoom = true;
  47081. this._isPanClick = false;
  47082. this.pinchInwards = true;
  47083. }
  47084. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47085. var _this = this;
  47086. var engine = this.camera.getEngine();
  47087. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47088. var pointA = null;
  47089. var pointB = null;
  47090. var previousPinchSquaredDistance = 0;
  47091. var initialDistance = 0;
  47092. var twoFingerActivityCount = 0;
  47093. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47094. this._pointerInput = function (p, s) {
  47095. var evt = p.event;
  47096. var isTouch = p.event.pointerType === "touch";
  47097. if (engine.isInVRExclusivePointerMode) {
  47098. return;
  47099. }
  47100. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47101. return;
  47102. }
  47103. var srcElement = (evt.srcElement || evt.target);
  47104. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47105. try {
  47106. srcElement.setPointerCapture(evt.pointerId);
  47107. }
  47108. catch (e) {
  47109. //Nothing to do with the error. Execution will continue.
  47110. }
  47111. // Manage panning with pan button click
  47112. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47113. // manage pointers
  47114. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47115. if (pointA === null) {
  47116. pointA = cacheSoloPointer;
  47117. }
  47118. else if (pointB === null) {
  47119. pointB = cacheSoloPointer;
  47120. }
  47121. if (!noPreventDefault) {
  47122. evt.preventDefault();
  47123. element.focus();
  47124. }
  47125. }
  47126. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47127. _this.camera.restoreState();
  47128. }
  47129. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47130. try {
  47131. srcElement.releasePointerCapture(evt.pointerId);
  47132. }
  47133. catch (e) {
  47134. //Nothing to do with the error.
  47135. }
  47136. cacheSoloPointer = null;
  47137. previousPinchSquaredDistance = 0;
  47138. previousMultiTouchPanPosition.isPaning = false;
  47139. previousMultiTouchPanPosition.isPinching = false;
  47140. twoFingerActivityCount = 0;
  47141. initialDistance = 0;
  47142. if (!isTouch) {
  47143. pointB = null; // Mouse and pen are mono pointer
  47144. }
  47145. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47146. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47147. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47148. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47149. if (engine._badOS) {
  47150. pointA = pointB = null;
  47151. }
  47152. else {
  47153. //only remove the impacted pointer in case of multitouch allowing on most
  47154. //platforms switching from rotate to zoom and pan seamlessly.
  47155. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47156. pointA = pointB;
  47157. pointB = null;
  47158. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47159. }
  47160. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47161. pointB = null;
  47162. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47163. }
  47164. else {
  47165. pointA = pointB = null;
  47166. }
  47167. }
  47168. if (!noPreventDefault) {
  47169. evt.preventDefault();
  47170. }
  47171. }
  47172. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47173. if (!noPreventDefault) {
  47174. evt.preventDefault();
  47175. }
  47176. // One button down
  47177. if (pointA && pointB === null && cacheSoloPointer) {
  47178. if (_this.panningSensibility !== 0 &&
  47179. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47180. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47181. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47182. }
  47183. else {
  47184. var offsetX = evt.clientX - cacheSoloPointer.x;
  47185. var offsetY = evt.clientY - cacheSoloPointer.y;
  47186. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47187. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47188. }
  47189. cacheSoloPointer.x = evt.clientX;
  47190. cacheSoloPointer.y = evt.clientY;
  47191. }
  47192. // Two buttons down: pinch/pan
  47193. else if (pointA && pointB) {
  47194. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47195. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47196. ed.x = evt.clientX;
  47197. ed.y = evt.clientY;
  47198. var direction = _this.pinchInwards ? 1 : -1;
  47199. var distX = pointA.x - pointB.x;
  47200. var distY = pointA.y - pointB.y;
  47201. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47202. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47203. if (previousPinchSquaredDistance === 0) {
  47204. initialDistance = pinchDistance;
  47205. previousPinchSquaredDistance = pinchSquaredDistance;
  47206. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47207. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47208. return;
  47209. }
  47210. if (_this.multiTouchPanAndZoom) {
  47211. if (_this.pinchDeltaPercentage) {
  47212. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47213. }
  47214. else {
  47215. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47216. (_this.pinchPrecision *
  47217. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47218. direction);
  47219. }
  47220. if (_this.panningSensibility !== 0) {
  47221. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47222. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47223. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47224. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47225. previousMultiTouchPanPosition.x = pointersCenterX;
  47226. previousMultiTouchPanPosition.y = pointersCenterY;
  47227. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47228. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47229. }
  47230. }
  47231. else {
  47232. twoFingerActivityCount++;
  47233. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47234. if (_this.pinchDeltaPercentage) {
  47235. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47236. }
  47237. else {
  47238. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47239. (_this.pinchPrecision *
  47240. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47241. direction);
  47242. }
  47243. previousMultiTouchPanPosition.isPaning = false;
  47244. previousMultiTouchPanPosition.isPinching = true;
  47245. }
  47246. else {
  47247. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47248. if (!previousMultiTouchPanPosition.isPaning) {
  47249. previousMultiTouchPanPosition.isPaning = true;
  47250. previousMultiTouchPanPosition.isPinching = false;
  47251. previousMultiTouchPanPosition.x = ed.x;
  47252. previousMultiTouchPanPosition.y = ed.y;
  47253. return;
  47254. }
  47255. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47256. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47257. }
  47258. }
  47259. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47260. previousMultiTouchPanPosition.x = ed.x;
  47261. previousMultiTouchPanPosition.y = ed.y;
  47262. }
  47263. }
  47264. previousPinchSquaredDistance = pinchSquaredDistance;
  47265. }
  47266. }
  47267. };
  47268. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47269. this._onContextMenu = function (evt) {
  47270. evt.preventDefault();
  47271. };
  47272. if (!this.camera._useCtrlForPanning) {
  47273. element.addEventListener("contextmenu", this._onContextMenu, false);
  47274. }
  47275. this._onLostFocus = function () {
  47276. //this._keys = [];
  47277. pointA = pointB = null;
  47278. previousPinchSquaredDistance = 0;
  47279. previousMultiTouchPanPosition.isPaning = false;
  47280. previousMultiTouchPanPosition.isPinching = false;
  47281. twoFingerActivityCount = 0;
  47282. cacheSoloPointer = null;
  47283. initialDistance = 0;
  47284. };
  47285. this._onMouseMove = function (evt) {
  47286. if (!engine.isPointerLock) {
  47287. return;
  47288. }
  47289. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47290. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47291. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47292. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47293. if (!noPreventDefault) {
  47294. evt.preventDefault();
  47295. }
  47296. };
  47297. this._onGestureStart = function (e) {
  47298. if (window.MSGesture === undefined) {
  47299. return;
  47300. }
  47301. if (!_this._MSGestureHandler) {
  47302. _this._MSGestureHandler = new MSGesture();
  47303. _this._MSGestureHandler.target = element;
  47304. }
  47305. _this._MSGestureHandler.addPointer(e.pointerId);
  47306. };
  47307. this._onGesture = function (e) {
  47308. _this.camera.radius *= e.scale;
  47309. if (e.preventDefault) {
  47310. if (!noPreventDefault) {
  47311. e.stopPropagation();
  47312. e.preventDefault();
  47313. }
  47314. }
  47315. };
  47316. element.addEventListener("mousemove", this._onMouseMove, false);
  47317. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47318. element.addEventListener("MSGestureChange", this._onGesture, false);
  47319. BABYLON.Tools.RegisterTopRootEvents([
  47320. { name: "blur", handler: this._onLostFocus }
  47321. ]);
  47322. };
  47323. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47324. if (this._onLostFocus) {
  47325. BABYLON.Tools.UnregisterTopRootEvents([
  47326. { name: "blur", handler: this._onLostFocus }
  47327. ]);
  47328. }
  47329. if (element && this._observer) {
  47330. this.camera.getScene().onPointerObservable.remove(this._observer);
  47331. this._observer = null;
  47332. if (this._onContextMenu) {
  47333. element.removeEventListener("contextmenu", this._onContextMenu);
  47334. }
  47335. if (this._onMouseMove) {
  47336. element.removeEventListener("mousemove", this._onMouseMove);
  47337. }
  47338. if (this._onGestureStart) {
  47339. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47340. }
  47341. if (this._onGesture) {
  47342. element.removeEventListener("MSGestureChange", this._onGesture);
  47343. }
  47344. this._isPanClick = false;
  47345. this.pinchInwards = true;
  47346. this._onMouseMove = null;
  47347. this._onGestureStart = null;
  47348. this._onGesture = null;
  47349. this._MSGestureHandler = null;
  47350. this._onLostFocus = null;
  47351. this._onContextMenu = null;
  47352. }
  47353. };
  47354. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47355. return "ArcRotateCameraPointersInput";
  47356. };
  47357. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47358. return "pointers";
  47359. };
  47360. __decorate([
  47361. BABYLON.serialize()
  47362. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47363. __decorate([
  47364. BABYLON.serialize()
  47365. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47366. __decorate([
  47367. BABYLON.serialize()
  47368. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47369. __decorate([
  47370. BABYLON.serialize()
  47371. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47372. __decorate([
  47373. BABYLON.serialize()
  47374. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47375. __decorate([
  47376. BABYLON.serialize()
  47377. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47378. __decorate([
  47379. BABYLON.serialize()
  47380. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47381. __decorate([
  47382. BABYLON.serialize()
  47383. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47384. return ArcRotateCameraPointersInput;
  47385. }());
  47386. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47387. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47388. })(BABYLON || (BABYLON = {}));
  47389. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47390. var BABYLON;
  47391. (function (BABYLON) {
  47392. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47393. __extends(ArcRotateCameraInputsManager, _super);
  47394. function ArcRotateCameraInputsManager(camera) {
  47395. return _super.call(this, camera) || this;
  47396. }
  47397. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47398. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47399. return this;
  47400. };
  47401. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47402. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47403. return this;
  47404. };
  47405. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47406. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47407. return this;
  47408. };
  47409. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47410. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47411. return this;
  47412. };
  47413. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47414. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47415. return this;
  47416. };
  47417. return ArcRotateCameraInputsManager;
  47418. }(BABYLON.CameraInputsManager));
  47419. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47420. })(BABYLON || (BABYLON = {}));
  47421. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47422. var BABYLON;
  47423. (function (BABYLON) {
  47424. var ArcRotateCamera = /** @class */ (function (_super) {
  47425. __extends(ArcRotateCamera, _super);
  47426. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47427. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47428. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47429. _this.inertialAlphaOffset = 0;
  47430. _this.inertialBetaOffset = 0;
  47431. _this.inertialRadiusOffset = 0;
  47432. _this.lowerAlphaLimit = null;
  47433. _this.upperAlphaLimit = null;
  47434. _this.lowerBetaLimit = 0.01;
  47435. _this.upperBetaLimit = Math.PI;
  47436. _this.lowerRadiusLimit = null;
  47437. _this.upperRadiusLimit = null;
  47438. _this.inertialPanningX = 0;
  47439. _this.inertialPanningY = 0;
  47440. _this.pinchToPanMaxDistance = 20;
  47441. _this.panningDistanceLimit = null;
  47442. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47443. _this.panningInertia = 0.9;
  47444. //-- end properties for backward compatibility for inputs
  47445. _this.zoomOnFactor = 1;
  47446. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47447. _this.allowUpsideDown = true;
  47448. _this._viewMatrix = new BABYLON.Matrix();
  47449. // Panning
  47450. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47451. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47452. _this.checkCollisions = false;
  47453. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47454. _this._previousPosition = BABYLON.Vector3.Zero();
  47455. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47456. _this._newPosition = BABYLON.Vector3.Zero();
  47457. _this._computationVector = BABYLON.Vector3.Zero();
  47458. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47459. if (collidedMesh === void 0) { collidedMesh = null; }
  47460. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47461. newPosition.multiplyInPlace(_this._collider._radius);
  47462. }
  47463. if (!collidedMesh) {
  47464. _this._previousPosition.copyFrom(_this.position);
  47465. }
  47466. else {
  47467. _this.setPosition(newPosition);
  47468. if (_this.onCollide) {
  47469. _this.onCollide(collidedMesh);
  47470. }
  47471. }
  47472. // Recompute because of constraints
  47473. var cosa = Math.cos(_this.alpha);
  47474. var sina = Math.sin(_this.alpha);
  47475. var cosb = Math.cos(_this.beta);
  47476. var sinb = Math.sin(_this.beta);
  47477. if (sinb === 0) {
  47478. sinb = 0.0001;
  47479. }
  47480. var target = _this._getTargetPosition();
  47481. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47482. target.addToRef(_this._computationVector, _this._newPosition);
  47483. _this.position.copyFrom(_this._newPosition);
  47484. var up = _this.upVector;
  47485. if (_this.allowUpsideDown && _this.beta < 0) {
  47486. up = up.clone();
  47487. up = up.negate();
  47488. }
  47489. _this._computeViewMatrix(_this.position, target, up);
  47490. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47491. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47492. _this._collisionTriggered = false;
  47493. };
  47494. _this._target = BABYLON.Vector3.Zero();
  47495. if (target) {
  47496. _this.setTarget(target);
  47497. }
  47498. _this.alpha = alpha;
  47499. _this.beta = beta;
  47500. _this.radius = radius;
  47501. _this.getViewMatrix();
  47502. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47503. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47504. return _this;
  47505. }
  47506. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47507. get: function () {
  47508. return this._target;
  47509. },
  47510. set: function (value) {
  47511. this.setTarget(value);
  47512. },
  47513. enumerable: true,
  47514. configurable: true
  47515. });
  47516. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47517. //-- begin properties for backward compatibility for inputs
  47518. get: function () {
  47519. var pointers = this.inputs.attached["pointers"];
  47520. if (pointers)
  47521. return pointers.angularSensibilityX;
  47522. return 0;
  47523. },
  47524. set: function (value) {
  47525. var pointers = this.inputs.attached["pointers"];
  47526. if (pointers) {
  47527. pointers.angularSensibilityX = value;
  47528. }
  47529. },
  47530. enumerable: true,
  47531. configurable: true
  47532. });
  47533. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47534. get: function () {
  47535. var pointers = this.inputs.attached["pointers"];
  47536. if (pointers)
  47537. return pointers.angularSensibilityY;
  47538. return 0;
  47539. },
  47540. set: function (value) {
  47541. var pointers = this.inputs.attached["pointers"];
  47542. if (pointers) {
  47543. pointers.angularSensibilityY = value;
  47544. }
  47545. },
  47546. enumerable: true,
  47547. configurable: true
  47548. });
  47549. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47550. get: function () {
  47551. var pointers = this.inputs.attached["pointers"];
  47552. if (pointers)
  47553. return pointers.pinchPrecision;
  47554. return 0;
  47555. },
  47556. set: function (value) {
  47557. var pointers = this.inputs.attached["pointers"];
  47558. if (pointers) {
  47559. pointers.pinchPrecision = value;
  47560. }
  47561. },
  47562. enumerable: true,
  47563. configurable: true
  47564. });
  47565. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47566. get: function () {
  47567. var pointers = this.inputs.attached["pointers"];
  47568. if (pointers)
  47569. return pointers.pinchDeltaPercentage;
  47570. return 0;
  47571. },
  47572. set: function (value) {
  47573. var pointers = this.inputs.attached["pointers"];
  47574. if (pointers) {
  47575. pointers.pinchDeltaPercentage = value;
  47576. }
  47577. },
  47578. enumerable: true,
  47579. configurable: true
  47580. });
  47581. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47582. get: function () {
  47583. var pointers = this.inputs.attached["pointers"];
  47584. if (pointers)
  47585. return pointers.panningSensibility;
  47586. return 0;
  47587. },
  47588. set: function (value) {
  47589. var pointers = this.inputs.attached["pointers"];
  47590. if (pointers) {
  47591. pointers.panningSensibility = value;
  47592. }
  47593. },
  47594. enumerable: true,
  47595. configurable: true
  47596. });
  47597. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47598. get: function () {
  47599. var keyboard = this.inputs.attached["keyboard"];
  47600. if (keyboard)
  47601. return keyboard.keysUp;
  47602. return [];
  47603. },
  47604. set: function (value) {
  47605. var keyboard = this.inputs.attached["keyboard"];
  47606. if (keyboard)
  47607. keyboard.keysUp = value;
  47608. },
  47609. enumerable: true,
  47610. configurable: true
  47611. });
  47612. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47613. get: function () {
  47614. var keyboard = this.inputs.attached["keyboard"];
  47615. if (keyboard)
  47616. return keyboard.keysDown;
  47617. return [];
  47618. },
  47619. set: function (value) {
  47620. var keyboard = this.inputs.attached["keyboard"];
  47621. if (keyboard)
  47622. keyboard.keysDown = value;
  47623. },
  47624. enumerable: true,
  47625. configurable: true
  47626. });
  47627. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47628. get: function () {
  47629. var keyboard = this.inputs.attached["keyboard"];
  47630. if (keyboard)
  47631. return keyboard.keysLeft;
  47632. return [];
  47633. },
  47634. set: function (value) {
  47635. var keyboard = this.inputs.attached["keyboard"];
  47636. if (keyboard)
  47637. keyboard.keysLeft = value;
  47638. },
  47639. enumerable: true,
  47640. configurable: true
  47641. });
  47642. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47643. get: function () {
  47644. var keyboard = this.inputs.attached["keyboard"];
  47645. if (keyboard)
  47646. return keyboard.keysRight;
  47647. return [];
  47648. },
  47649. set: function (value) {
  47650. var keyboard = this.inputs.attached["keyboard"];
  47651. if (keyboard)
  47652. keyboard.keysRight = value;
  47653. },
  47654. enumerable: true,
  47655. configurable: true
  47656. });
  47657. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47658. get: function () {
  47659. var mousewheel = this.inputs.attached["mousewheel"];
  47660. if (mousewheel)
  47661. return mousewheel.wheelPrecision;
  47662. return 0;
  47663. },
  47664. set: function (value) {
  47665. var mousewheel = this.inputs.attached["mousewheel"];
  47666. if (mousewheel)
  47667. mousewheel.wheelPrecision = value;
  47668. },
  47669. enumerable: true,
  47670. configurable: true
  47671. });
  47672. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47673. get: function () {
  47674. var mousewheel = this.inputs.attached["mousewheel"];
  47675. if (mousewheel)
  47676. return mousewheel.wheelDeltaPercentage;
  47677. return 0;
  47678. },
  47679. set: function (value) {
  47680. var mousewheel = this.inputs.attached["mousewheel"];
  47681. if (mousewheel)
  47682. mousewheel.wheelDeltaPercentage = value;
  47683. },
  47684. enumerable: true,
  47685. configurable: true
  47686. });
  47687. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47688. get: function () {
  47689. return this._bouncingBehavior;
  47690. },
  47691. enumerable: true,
  47692. configurable: true
  47693. });
  47694. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47695. get: function () {
  47696. return this._bouncingBehavior != null;
  47697. },
  47698. set: function (value) {
  47699. if (value === this.useBouncingBehavior) {
  47700. return;
  47701. }
  47702. if (value) {
  47703. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47704. this.addBehavior(this._bouncingBehavior);
  47705. }
  47706. else if (this._bouncingBehavior) {
  47707. this.removeBehavior(this._bouncingBehavior);
  47708. this._bouncingBehavior = null;
  47709. }
  47710. },
  47711. enumerable: true,
  47712. configurable: true
  47713. });
  47714. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47715. get: function () {
  47716. return this._framingBehavior;
  47717. },
  47718. enumerable: true,
  47719. configurable: true
  47720. });
  47721. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47722. get: function () {
  47723. return this._framingBehavior != null;
  47724. },
  47725. set: function (value) {
  47726. if (value === this.useFramingBehavior) {
  47727. return;
  47728. }
  47729. if (value) {
  47730. this._framingBehavior = new BABYLON.FramingBehavior();
  47731. this.addBehavior(this._framingBehavior);
  47732. }
  47733. else if (this._framingBehavior) {
  47734. this.removeBehavior(this._framingBehavior);
  47735. this._framingBehavior = null;
  47736. }
  47737. },
  47738. enumerable: true,
  47739. configurable: true
  47740. });
  47741. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47742. get: function () {
  47743. return this._autoRotationBehavior;
  47744. },
  47745. enumerable: true,
  47746. configurable: true
  47747. });
  47748. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47749. get: function () {
  47750. return this._autoRotationBehavior != null;
  47751. },
  47752. set: function (value) {
  47753. if (value === this.useAutoRotationBehavior) {
  47754. return;
  47755. }
  47756. if (value) {
  47757. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47758. this.addBehavior(this._autoRotationBehavior);
  47759. }
  47760. else if (this._autoRotationBehavior) {
  47761. this.removeBehavior(this._autoRotationBehavior);
  47762. this._autoRotationBehavior = null;
  47763. }
  47764. },
  47765. enumerable: true,
  47766. configurable: true
  47767. });
  47768. // Cache
  47769. ArcRotateCamera.prototype._initCache = function () {
  47770. _super.prototype._initCache.call(this);
  47771. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47772. this._cache.alpha = undefined;
  47773. this._cache.beta = undefined;
  47774. this._cache.radius = undefined;
  47775. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47776. };
  47777. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47778. if (!ignoreParentClass) {
  47779. _super.prototype._updateCache.call(this);
  47780. }
  47781. this._cache._target.copyFrom(this._getTargetPosition());
  47782. this._cache.alpha = this.alpha;
  47783. this._cache.beta = this.beta;
  47784. this._cache.radius = this.radius;
  47785. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47786. };
  47787. ArcRotateCamera.prototype._getTargetPosition = function () {
  47788. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47789. var pos = this._targetHost.getAbsolutePosition();
  47790. if (this._targetBoundingCenter) {
  47791. pos.addToRef(this._targetBoundingCenter, this._target);
  47792. }
  47793. else {
  47794. this._target.copyFrom(pos);
  47795. }
  47796. }
  47797. var lockedTargetPosition = this._getLockedTargetPosition();
  47798. if (lockedTargetPosition) {
  47799. return lockedTargetPosition;
  47800. }
  47801. return this._target;
  47802. };
  47803. ArcRotateCamera.prototype.storeState = function () {
  47804. this._storedAlpha = this.alpha;
  47805. this._storedBeta = this.beta;
  47806. this._storedRadius = this.radius;
  47807. this._storedTarget = this._getTargetPosition().clone();
  47808. return _super.prototype.storeState.call(this);
  47809. };
  47810. /**
  47811. * Restored camera state. You must call storeState() first
  47812. */
  47813. ArcRotateCamera.prototype._restoreStateValues = function () {
  47814. if (!_super.prototype._restoreStateValues.call(this)) {
  47815. return false;
  47816. }
  47817. this.alpha = this._storedAlpha;
  47818. this.beta = this._storedBeta;
  47819. this.radius = this._storedRadius;
  47820. this.setTarget(this._storedTarget.clone());
  47821. this.inertialAlphaOffset = 0;
  47822. this.inertialBetaOffset = 0;
  47823. this.inertialRadiusOffset = 0;
  47824. this.inertialPanningX = 0;
  47825. this.inertialPanningY = 0;
  47826. return true;
  47827. };
  47828. // Synchronized
  47829. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47830. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47831. return false;
  47832. return this._cache._target.equals(this._getTargetPosition())
  47833. && this._cache.alpha === this.alpha
  47834. && this._cache.beta === this.beta
  47835. && this._cache.radius === this.radius
  47836. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47837. };
  47838. // Methods
  47839. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47840. var _this = this;
  47841. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47842. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47843. this._useCtrlForPanning = useCtrlForPanning;
  47844. this._panningMouseButton = panningMouseButton;
  47845. this.inputs.attachElement(element, noPreventDefault);
  47846. this._reset = function () {
  47847. _this.inertialAlphaOffset = 0;
  47848. _this.inertialBetaOffset = 0;
  47849. _this.inertialRadiusOffset = 0;
  47850. _this.inertialPanningX = 0;
  47851. _this.inertialPanningY = 0;
  47852. };
  47853. };
  47854. ArcRotateCamera.prototype.detachControl = function (element) {
  47855. this.inputs.detachElement(element);
  47856. if (this._reset) {
  47857. this._reset();
  47858. }
  47859. };
  47860. ArcRotateCamera.prototype._checkInputs = function () {
  47861. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47862. if (this._collisionTriggered) {
  47863. return;
  47864. }
  47865. this.inputs.checkInputs();
  47866. // Inertia
  47867. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47868. var inertialAlphaOffset = this.inertialAlphaOffset;
  47869. if (this.beta <= 0)
  47870. inertialAlphaOffset *= -1;
  47871. if (this.getScene().useRightHandedSystem)
  47872. inertialAlphaOffset *= -1;
  47873. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47874. inertialAlphaOffset *= -1;
  47875. this.alpha += inertialAlphaOffset;
  47876. this.beta += this.inertialBetaOffset;
  47877. this.radius -= this.inertialRadiusOffset;
  47878. this.inertialAlphaOffset *= this.inertia;
  47879. this.inertialBetaOffset *= this.inertia;
  47880. this.inertialRadiusOffset *= this.inertia;
  47881. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47882. this.inertialAlphaOffset = 0;
  47883. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47884. this.inertialBetaOffset = 0;
  47885. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47886. this.inertialRadiusOffset = 0;
  47887. }
  47888. // Panning inertia
  47889. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47890. if (!this._localDirection) {
  47891. this._localDirection = BABYLON.Vector3.Zero();
  47892. this._transformedDirection = BABYLON.Vector3.Zero();
  47893. }
  47894. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47895. this._localDirection.multiplyInPlace(this.panningAxis);
  47896. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47897. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47898. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47899. if (!this.panningAxis.y) {
  47900. this._transformedDirection.y = 0;
  47901. }
  47902. if (!this._targetHost) {
  47903. if (this.panningDistanceLimit) {
  47904. this._transformedDirection.addInPlace(this._target);
  47905. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47906. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47907. this._target.copyFrom(this._transformedDirection);
  47908. }
  47909. }
  47910. else {
  47911. this._target.addInPlace(this._transformedDirection);
  47912. }
  47913. }
  47914. this.inertialPanningX *= this.panningInertia;
  47915. this.inertialPanningY *= this.panningInertia;
  47916. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47917. this.inertialPanningX = 0;
  47918. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47919. this.inertialPanningY = 0;
  47920. }
  47921. // Limits
  47922. this._checkLimits();
  47923. _super.prototype._checkInputs.call(this);
  47924. };
  47925. ArcRotateCamera.prototype._checkLimits = function () {
  47926. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47927. if (this.allowUpsideDown && this.beta > Math.PI) {
  47928. this.beta = this.beta - (2 * Math.PI);
  47929. }
  47930. }
  47931. else {
  47932. if (this.beta < this.lowerBetaLimit) {
  47933. this.beta = this.lowerBetaLimit;
  47934. }
  47935. }
  47936. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47937. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47938. this.beta = this.beta + (2 * Math.PI);
  47939. }
  47940. }
  47941. else {
  47942. if (this.beta > this.upperBetaLimit) {
  47943. this.beta = this.upperBetaLimit;
  47944. }
  47945. }
  47946. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47947. this.alpha = this.lowerAlphaLimit;
  47948. }
  47949. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47950. this.alpha = this.upperAlphaLimit;
  47951. }
  47952. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47953. this.radius = this.lowerRadiusLimit;
  47954. }
  47955. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47956. this.radius = this.upperRadiusLimit;
  47957. }
  47958. };
  47959. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47960. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47961. this.radius = this._computationVector.length();
  47962. if (this.radius === 0) {
  47963. this.radius = 0.0001; // Just to avoid division by zero
  47964. }
  47965. // Alpha
  47966. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47967. if (this._computationVector.z < 0) {
  47968. this.alpha = 2 * Math.PI - this.alpha;
  47969. }
  47970. // Beta
  47971. this.beta = Math.acos(this._computationVector.y / this.radius);
  47972. this._checkLimits();
  47973. };
  47974. ArcRotateCamera.prototype.setPosition = function (position) {
  47975. if (this.position.equals(position)) {
  47976. return;
  47977. }
  47978. this.position.copyFrom(position);
  47979. this.rebuildAnglesAndRadius();
  47980. };
  47981. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47982. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47983. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47984. if (target.getBoundingInfo) {
  47985. if (toBoundingCenter) {
  47986. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47987. }
  47988. else {
  47989. this._targetBoundingCenter = null;
  47990. }
  47991. this._targetHost = target;
  47992. this._target = this._getTargetPosition();
  47993. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47994. }
  47995. else {
  47996. var newTarget = target;
  47997. var currentTarget = this._getTargetPosition();
  47998. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47999. return;
  48000. }
  48001. this._targetHost = null;
  48002. this._target = newTarget;
  48003. this._targetBoundingCenter = null;
  48004. this.onMeshTargetChangedObservable.notifyObservers(null);
  48005. }
  48006. this.rebuildAnglesAndRadius();
  48007. };
  48008. ArcRotateCamera.prototype._getViewMatrix = function () {
  48009. // Compute
  48010. var cosa = Math.cos(this.alpha);
  48011. var sina = Math.sin(this.alpha);
  48012. var cosb = Math.cos(this.beta);
  48013. var sinb = Math.sin(this.beta);
  48014. if (sinb === 0) {
  48015. sinb = 0.0001;
  48016. }
  48017. var target = this._getTargetPosition();
  48018. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48019. target.addToRef(this._computationVector, this._newPosition);
  48020. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48021. if (!this._collider) {
  48022. this._collider = new BABYLON.Collider();
  48023. }
  48024. this._collider._radius = this.collisionRadius;
  48025. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48026. this._collisionTriggered = true;
  48027. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48028. }
  48029. else {
  48030. this.position.copyFrom(this._newPosition);
  48031. var up = this.upVector;
  48032. if (this.allowUpsideDown && sinb < 0) {
  48033. up = up.clone();
  48034. up = up.negate();
  48035. }
  48036. this._computeViewMatrix(this.position, target, up);
  48037. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48038. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48039. }
  48040. this._currentTarget = target;
  48041. return this._viewMatrix;
  48042. };
  48043. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48044. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48045. meshes = meshes || this.getScene().meshes;
  48046. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48047. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48048. this.radius = distance * this.zoomOnFactor;
  48049. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48050. };
  48051. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48052. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48053. var meshesOrMinMaxVector;
  48054. var distance;
  48055. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48056. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48057. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48058. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48059. }
  48060. else { //minMaxVector and distance
  48061. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48062. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48063. distance = minMaxVectorAndDistance.distance;
  48064. }
  48065. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48066. if (!doNotUpdateMaxZ) {
  48067. this.maxZ = distance * 2;
  48068. }
  48069. };
  48070. /**
  48071. * @override
  48072. * Override Camera.createRigCamera
  48073. */
  48074. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48075. var alphaShift = 0;
  48076. switch (this.cameraRigMode) {
  48077. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48078. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48079. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48080. case BABYLON.Camera.RIG_MODE_VR:
  48081. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48082. break;
  48083. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48084. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48085. break;
  48086. }
  48087. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48088. rigCam._cameraRigParams = {};
  48089. return rigCam;
  48090. };
  48091. /**
  48092. * @override
  48093. * Override Camera._updateRigCameras
  48094. */
  48095. ArcRotateCamera.prototype._updateRigCameras = function () {
  48096. var camLeft = this._rigCameras[0];
  48097. var camRight = this._rigCameras[1];
  48098. camLeft.beta = camRight.beta = this.beta;
  48099. camLeft.radius = camRight.radius = this.radius;
  48100. switch (this.cameraRigMode) {
  48101. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48102. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48103. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48104. case BABYLON.Camera.RIG_MODE_VR:
  48105. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48106. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48107. break;
  48108. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48109. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48110. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48111. break;
  48112. }
  48113. _super.prototype._updateRigCameras.call(this);
  48114. };
  48115. ArcRotateCamera.prototype.dispose = function () {
  48116. this.inputs.clear();
  48117. _super.prototype.dispose.call(this);
  48118. };
  48119. ArcRotateCamera.prototype.getClassName = function () {
  48120. return "ArcRotateCamera";
  48121. };
  48122. __decorate([
  48123. BABYLON.serialize()
  48124. ], ArcRotateCamera.prototype, "alpha", void 0);
  48125. __decorate([
  48126. BABYLON.serialize()
  48127. ], ArcRotateCamera.prototype, "beta", void 0);
  48128. __decorate([
  48129. BABYLON.serialize()
  48130. ], ArcRotateCamera.prototype, "radius", void 0);
  48131. __decorate([
  48132. BABYLON.serializeAsVector3("target")
  48133. ], ArcRotateCamera.prototype, "_target", void 0);
  48134. __decorate([
  48135. BABYLON.serialize()
  48136. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48137. __decorate([
  48138. BABYLON.serialize()
  48139. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48140. __decorate([
  48141. BABYLON.serialize()
  48142. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48143. __decorate([
  48144. BABYLON.serialize()
  48145. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48146. __decorate([
  48147. BABYLON.serialize()
  48148. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48149. __decorate([
  48150. BABYLON.serialize()
  48151. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48152. __decorate([
  48153. BABYLON.serialize()
  48154. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48155. __decorate([
  48156. BABYLON.serialize()
  48157. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48158. __decorate([
  48159. BABYLON.serialize()
  48160. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48161. __decorate([
  48162. BABYLON.serialize()
  48163. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48164. __decorate([
  48165. BABYLON.serialize()
  48166. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48167. __decorate([
  48168. BABYLON.serialize()
  48169. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48170. __decorate([
  48171. BABYLON.serialize()
  48172. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48173. __decorate([
  48174. BABYLON.serializeAsVector3()
  48175. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48176. __decorate([
  48177. BABYLON.serialize()
  48178. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48179. __decorate([
  48180. BABYLON.serialize()
  48181. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48182. __decorate([
  48183. BABYLON.serialize()
  48184. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48185. return ArcRotateCamera;
  48186. }(BABYLON.TargetCamera));
  48187. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48188. })(BABYLON || (BABYLON = {}));
  48189. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48190. var BABYLON;
  48191. (function (BABYLON) {
  48192. /**
  48193. * The HemisphericLight simulates the ambient environment light,
  48194. * so the passed direction is the light reflection direction, not the incoming direction.
  48195. */
  48196. var HemisphericLight = /** @class */ (function (_super) {
  48197. __extends(HemisphericLight, _super);
  48198. /**
  48199. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48200. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48201. * The HemisphericLight can't cast shadows.
  48202. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48203. * @param name The friendly name of the light
  48204. * @param direction The direction of the light reflection
  48205. * @param scene The scene the light belongs to
  48206. */
  48207. function HemisphericLight(name, direction, scene) {
  48208. var _this = _super.call(this, name, scene) || this;
  48209. /**
  48210. * The groundColor is the light in the opposite direction to the one specified during creation.
  48211. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  48212. */
  48213. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48214. _this.direction = direction || BABYLON.Vector3.Up();
  48215. return _this;
  48216. }
  48217. HemisphericLight.prototype._buildUniformLayout = function () {
  48218. this._uniformBuffer.addUniform("vLightData", 4);
  48219. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48220. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48221. this._uniformBuffer.addUniform("vLightGround", 3);
  48222. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48223. this._uniformBuffer.addUniform("depthValues", 2);
  48224. this._uniformBuffer.create();
  48225. };
  48226. /**
  48227. * Returns the string "HemisphericLight".
  48228. * @return The class name
  48229. */
  48230. HemisphericLight.prototype.getClassName = function () {
  48231. return "HemisphericLight";
  48232. };
  48233. /**
  48234. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48235. * Returns the updated direction.
  48236. * @param target The target the direction should point to
  48237. * @return The computed direction
  48238. */
  48239. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48240. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48241. return this.direction;
  48242. };
  48243. /**
  48244. * Returns the shadow generator associated to the light.
  48245. * @returns Always null for hemispheric lights because it does not support shadows.
  48246. */
  48247. HemisphericLight.prototype.getShadowGenerator = function () {
  48248. return null;
  48249. };
  48250. /**
  48251. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48252. * @param effect The effect to update
  48253. * @param lightIndex The index of the light in the effect to update
  48254. * @returns The hemispheric light
  48255. */
  48256. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48257. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48258. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48259. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48260. return this;
  48261. };
  48262. /**
  48263. * @hidden internal use only.
  48264. */
  48265. HemisphericLight.prototype._getWorldMatrix = function () {
  48266. if (!this._worldMatrix) {
  48267. this._worldMatrix = BABYLON.Matrix.Identity();
  48268. }
  48269. return this._worldMatrix;
  48270. };
  48271. /**
  48272. * Returns the integer 3.
  48273. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48274. */
  48275. HemisphericLight.prototype.getTypeID = function () {
  48276. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48277. };
  48278. __decorate([
  48279. BABYLON.serializeAsColor3()
  48280. ], HemisphericLight.prototype, "groundColor", void 0);
  48281. __decorate([
  48282. BABYLON.serializeAsVector3()
  48283. ], HemisphericLight.prototype, "direction", void 0);
  48284. return HemisphericLight;
  48285. }(BABYLON.Light));
  48286. BABYLON.HemisphericLight = HemisphericLight;
  48287. })(BABYLON || (BABYLON = {}));
  48288. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48289. var BABYLON;
  48290. (function (BABYLON) {
  48291. /**
  48292. * Base implementation IShadowLight
  48293. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48294. */
  48295. var ShadowLight = /** @class */ (function (_super) {
  48296. __extends(ShadowLight, _super);
  48297. function ShadowLight() {
  48298. var _this = _super !== null && _super.apply(this, arguments) || this;
  48299. _this._needProjectionMatrixCompute = true;
  48300. return _this;
  48301. }
  48302. ShadowLight.prototype._setPosition = function (value) {
  48303. this._position = value;
  48304. };
  48305. Object.defineProperty(ShadowLight.prototype, "position", {
  48306. /**
  48307. * Sets the position the shadow will be casted from. Also use as the light position for both
  48308. * point and spot lights.
  48309. */
  48310. get: function () {
  48311. return this._position;
  48312. },
  48313. /**
  48314. * Sets the position the shadow will be casted from. Also use as the light position for both
  48315. * point and spot lights.
  48316. */
  48317. set: function (value) {
  48318. this._setPosition(value);
  48319. },
  48320. enumerable: true,
  48321. configurable: true
  48322. });
  48323. ShadowLight.prototype._setDirection = function (value) {
  48324. this._direction = value;
  48325. };
  48326. Object.defineProperty(ShadowLight.prototype, "direction", {
  48327. /**
  48328. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48329. * Also use as the light direction on spot and directional lights.
  48330. */
  48331. get: function () {
  48332. return this._direction;
  48333. },
  48334. /**
  48335. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48336. * Also use as the light direction on spot and directional lights.
  48337. */
  48338. set: function (value) {
  48339. this._setDirection(value);
  48340. },
  48341. enumerable: true,
  48342. configurable: true
  48343. });
  48344. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48345. /**
  48346. * Gets the shadow projection clipping minimum z value.
  48347. */
  48348. get: function () {
  48349. return this._shadowMinZ;
  48350. },
  48351. /**
  48352. * Sets the shadow projection clipping minimum z value.
  48353. */
  48354. set: function (value) {
  48355. this._shadowMinZ = value;
  48356. this.forceProjectionMatrixCompute();
  48357. },
  48358. enumerable: true,
  48359. configurable: true
  48360. });
  48361. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48362. /**
  48363. * Sets the shadow projection clipping maximum z value.
  48364. */
  48365. get: function () {
  48366. return this._shadowMaxZ;
  48367. },
  48368. /**
  48369. * Gets the shadow projection clipping maximum z value.
  48370. */
  48371. set: function (value) {
  48372. this._shadowMaxZ = value;
  48373. this.forceProjectionMatrixCompute();
  48374. },
  48375. enumerable: true,
  48376. configurable: true
  48377. });
  48378. /**
  48379. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48380. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48381. */
  48382. ShadowLight.prototype.computeTransformedInformation = function () {
  48383. if (this.parent && this.parent.getWorldMatrix) {
  48384. if (!this.transformedPosition) {
  48385. this.transformedPosition = BABYLON.Vector3.Zero();
  48386. }
  48387. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48388. // In case the direction is present.
  48389. if (this.direction) {
  48390. if (!this.transformedDirection) {
  48391. this.transformedDirection = BABYLON.Vector3.Zero();
  48392. }
  48393. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48394. }
  48395. return true;
  48396. }
  48397. return false;
  48398. };
  48399. /**
  48400. * Return the depth scale used for the shadow map.
  48401. * @returns the depth scale.
  48402. */
  48403. ShadowLight.prototype.getDepthScale = function () {
  48404. return 50.0;
  48405. };
  48406. /**
  48407. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48408. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48409. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48410. */
  48411. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48412. return this.transformedDirection ? this.transformedDirection : this.direction;
  48413. };
  48414. /**
  48415. * Returns the ShadowLight absolute position in the World.
  48416. * @returns the position vector in world space
  48417. */
  48418. ShadowLight.prototype.getAbsolutePosition = function () {
  48419. return this.transformedPosition ? this.transformedPosition : this.position;
  48420. };
  48421. /**
  48422. * Sets the ShadowLight direction toward the passed target.
  48423. * @param target The point tot target in local space
  48424. * @returns the updated ShadowLight direction
  48425. */
  48426. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48427. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48428. return this.direction;
  48429. };
  48430. /**
  48431. * Returns the light rotation in euler definition.
  48432. * @returns the x y z rotation in local space.
  48433. */
  48434. ShadowLight.prototype.getRotation = function () {
  48435. this.direction.normalize();
  48436. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48437. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48438. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48439. };
  48440. /**
  48441. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48442. * @returns true if a cube texture needs to be use
  48443. */
  48444. ShadowLight.prototype.needCube = function () {
  48445. return false;
  48446. };
  48447. /**
  48448. * Detects if the projection matrix requires to be recomputed this frame.
  48449. * @returns true if it requires to be recomputed otherwise, false.
  48450. */
  48451. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48452. return this._needProjectionMatrixCompute;
  48453. };
  48454. /**
  48455. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48456. */
  48457. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48458. this._needProjectionMatrixCompute = true;
  48459. };
  48460. /**
  48461. * Get the world matrix of the sahdow lights.
  48462. * @hidden Internal Use Only
  48463. */
  48464. ShadowLight.prototype._getWorldMatrix = function () {
  48465. if (!this._worldMatrix) {
  48466. this._worldMatrix = BABYLON.Matrix.Identity();
  48467. }
  48468. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48469. return this._worldMatrix;
  48470. };
  48471. /**
  48472. * Gets the minZ used for shadow according to both the scene and the light.
  48473. * @param activeCamera The camera we are returning the min for
  48474. * @returns the depth min z
  48475. */
  48476. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48477. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48478. };
  48479. /**
  48480. * Gets the maxZ used for shadow according to both the scene and the light.
  48481. * @param activeCamera The camera we are returning the max for
  48482. * @returns the depth max z
  48483. */
  48484. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48485. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48486. };
  48487. /**
  48488. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48489. * @param matrix The materix to updated with the projection information
  48490. * @param viewMatrix The transform matrix of the light
  48491. * @param renderList The list of mesh to render in the map
  48492. * @returns The current light
  48493. */
  48494. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48495. if (this.customProjectionMatrixBuilder) {
  48496. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48497. }
  48498. else {
  48499. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48500. }
  48501. return this;
  48502. };
  48503. __decorate([
  48504. BABYLON.serializeAsVector3()
  48505. ], ShadowLight.prototype, "position", null);
  48506. __decorate([
  48507. BABYLON.serializeAsVector3()
  48508. ], ShadowLight.prototype, "direction", null);
  48509. __decorate([
  48510. BABYLON.serialize()
  48511. ], ShadowLight.prototype, "shadowMinZ", null);
  48512. __decorate([
  48513. BABYLON.serialize()
  48514. ], ShadowLight.prototype, "shadowMaxZ", null);
  48515. return ShadowLight;
  48516. }(BABYLON.Light));
  48517. BABYLON.ShadowLight = ShadowLight;
  48518. })(BABYLON || (BABYLON = {}));
  48519. //# sourceMappingURL=babylon.shadowLight.js.map
  48520. var BABYLON;
  48521. (function (BABYLON) {
  48522. /**
  48523. * A point light is a light defined by an unique point in world space.
  48524. * The light is emitted in every direction from this point.
  48525. * A good example of a point light is a standard light bulb.
  48526. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48527. */
  48528. var PointLight = /** @class */ (function (_super) {
  48529. __extends(PointLight, _super);
  48530. /**
  48531. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48532. * A PointLight emits the light in every direction.
  48533. * It can cast shadows.
  48534. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48535. * ```javascript
  48536. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48537. * ```
  48538. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48539. * @param name The light friendly name
  48540. * @param position The position of the point light in the scene
  48541. * @param scene The scene the lights belongs to
  48542. */
  48543. function PointLight(name, position, scene) {
  48544. var _this = _super.call(this, name, scene) || this;
  48545. _this._shadowAngle = Math.PI / 2;
  48546. _this.position = position;
  48547. return _this;
  48548. }
  48549. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48550. /**
  48551. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48552. * This specifies what angle the shadow will use to be created.
  48553. *
  48554. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48555. */
  48556. get: function () {
  48557. return this._shadowAngle;
  48558. },
  48559. /**
  48560. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48561. * This specifies what angle the shadow will use to be created.
  48562. *
  48563. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48564. */
  48565. set: function (value) {
  48566. this._shadowAngle = value;
  48567. this.forceProjectionMatrixCompute();
  48568. },
  48569. enumerable: true,
  48570. configurable: true
  48571. });
  48572. Object.defineProperty(PointLight.prototype, "direction", {
  48573. /**
  48574. * Gets the direction if it has been set.
  48575. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48576. */
  48577. get: function () {
  48578. return this._direction;
  48579. },
  48580. /**
  48581. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48582. */
  48583. set: function (value) {
  48584. var previousNeedCube = this.needCube();
  48585. this._direction = value;
  48586. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48587. this._shadowGenerator.recreateShadowMap();
  48588. }
  48589. },
  48590. enumerable: true,
  48591. configurable: true
  48592. });
  48593. /**
  48594. * Returns the string "PointLight"
  48595. * @returns the class name
  48596. */
  48597. PointLight.prototype.getClassName = function () {
  48598. return "PointLight";
  48599. };
  48600. /**
  48601. * Returns the integer 0.
  48602. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48603. */
  48604. PointLight.prototype.getTypeID = function () {
  48605. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48606. };
  48607. /**
  48608. * Specifies wether or not the shadowmap should be a cube texture.
  48609. * @returns true if the shadowmap needs to be a cube texture.
  48610. */
  48611. PointLight.prototype.needCube = function () {
  48612. return !this.direction;
  48613. };
  48614. /**
  48615. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48616. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48617. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48618. */
  48619. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48620. if (this.direction) {
  48621. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48622. }
  48623. else {
  48624. switch (faceIndex) {
  48625. case 0:
  48626. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48627. case 1:
  48628. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48629. case 2:
  48630. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48631. case 3:
  48632. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48633. case 4:
  48634. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48635. case 5:
  48636. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48637. }
  48638. }
  48639. return BABYLON.Vector3.Zero();
  48640. };
  48641. /**
  48642. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48643. * - fov = PI / 2
  48644. * - aspect ratio : 1.0
  48645. * - z-near and far equal to the active camera minZ and maxZ.
  48646. * Returns the PointLight.
  48647. */
  48648. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48649. var activeCamera = this.getScene().activeCamera;
  48650. if (!activeCamera) {
  48651. return;
  48652. }
  48653. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48654. };
  48655. PointLight.prototype._buildUniformLayout = function () {
  48656. this._uniformBuffer.addUniform("vLightData", 4);
  48657. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48658. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48659. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48660. this._uniformBuffer.addUniform("depthValues", 2);
  48661. this._uniformBuffer.create();
  48662. };
  48663. /**
  48664. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48665. * @param effect The effect to update
  48666. * @param lightIndex The index of the light in the effect to update
  48667. * @returns The point light
  48668. */
  48669. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48670. if (this.computeTransformedInformation()) {
  48671. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48672. return this;
  48673. }
  48674. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48675. return this;
  48676. };
  48677. __decorate([
  48678. BABYLON.serialize()
  48679. ], PointLight.prototype, "shadowAngle", null);
  48680. return PointLight;
  48681. }(BABYLON.ShadowLight));
  48682. BABYLON.PointLight = PointLight;
  48683. })(BABYLON || (BABYLON = {}));
  48684. //# sourceMappingURL=babylon.pointLight.js.map
  48685. var BABYLON;
  48686. (function (BABYLON) {
  48687. /**
  48688. * A directional light is defined by a direction (what a surprise!).
  48689. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48690. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  48691. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48692. */
  48693. var DirectionalLight = /** @class */ (function (_super) {
  48694. __extends(DirectionalLight, _super);
  48695. /**
  48696. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48697. * The directional light is emitted from everywhere in the given direction.
  48698. * It can cast shawdows.
  48699. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48700. * @param name The friendly name of the light
  48701. * @param direction The direction of the light
  48702. * @param scene The scene the light belongs to
  48703. */
  48704. function DirectionalLight(name, direction, scene) {
  48705. var _this = _super.call(this, name, scene) || this;
  48706. _this._shadowFrustumSize = 0;
  48707. _this._shadowOrthoScale = 0.1;
  48708. /**
  48709. * Automatically compute the projection matrix to best fit (including all the casters)
  48710. * on each frame.
  48711. */
  48712. _this.autoUpdateExtends = true;
  48713. // Cache
  48714. _this._orthoLeft = Number.MAX_VALUE;
  48715. _this._orthoRight = Number.MIN_VALUE;
  48716. _this._orthoTop = Number.MIN_VALUE;
  48717. _this._orthoBottom = Number.MAX_VALUE;
  48718. _this.position = direction.scale(-1.0);
  48719. _this.direction = direction;
  48720. return _this;
  48721. }
  48722. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48723. /**
  48724. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48725. */
  48726. get: function () {
  48727. return this._shadowFrustumSize;
  48728. },
  48729. /**
  48730. * Specifies a fix frustum size for the shadow generation.
  48731. */
  48732. set: function (value) {
  48733. this._shadowFrustumSize = value;
  48734. this.forceProjectionMatrixCompute();
  48735. },
  48736. enumerable: true,
  48737. configurable: true
  48738. });
  48739. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48740. /**
  48741. * Gets the shadow projection scale against the optimal computed one.
  48742. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48743. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48744. */
  48745. get: function () {
  48746. return this._shadowOrthoScale;
  48747. },
  48748. /**
  48749. * Sets the shadow projection scale against the optimal computed one.
  48750. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48751. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48752. */
  48753. set: function (value) {
  48754. this._shadowOrthoScale = value;
  48755. this.forceProjectionMatrixCompute();
  48756. },
  48757. enumerable: true,
  48758. configurable: true
  48759. });
  48760. /**
  48761. * Returns the string "DirectionalLight".
  48762. * @return The class name
  48763. */
  48764. DirectionalLight.prototype.getClassName = function () {
  48765. return "DirectionalLight";
  48766. };
  48767. /**
  48768. * Returns the integer 1.
  48769. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48770. */
  48771. DirectionalLight.prototype.getTypeID = function () {
  48772. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48773. };
  48774. /**
  48775. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48776. * Returns the DirectionalLight Shadow projection matrix.
  48777. */
  48778. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48779. if (this.shadowFrustumSize > 0) {
  48780. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48781. }
  48782. else {
  48783. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48784. }
  48785. };
  48786. /**
  48787. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48788. * Returns the DirectionalLight Shadow projection matrix.
  48789. */
  48790. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48791. var activeCamera = this.getScene().activeCamera;
  48792. if (!activeCamera) {
  48793. return;
  48794. }
  48795. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48796. };
  48797. /**
  48798. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48799. * Returns the DirectionalLight Shadow projection matrix.
  48800. */
  48801. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48802. var activeCamera = this.getScene().activeCamera;
  48803. if (!activeCamera) {
  48804. return;
  48805. }
  48806. // Check extends
  48807. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48808. var tempVector3 = BABYLON.Vector3.Zero();
  48809. this._orthoLeft = Number.MAX_VALUE;
  48810. this._orthoRight = Number.MIN_VALUE;
  48811. this._orthoTop = Number.MIN_VALUE;
  48812. this._orthoBottom = Number.MAX_VALUE;
  48813. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48814. var mesh = renderList[meshIndex];
  48815. if (!mesh) {
  48816. continue;
  48817. }
  48818. var boundingInfo = mesh.getBoundingInfo();
  48819. var boundingBox = boundingInfo.boundingBox;
  48820. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48821. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48822. if (tempVector3.x < this._orthoLeft)
  48823. this._orthoLeft = tempVector3.x;
  48824. if (tempVector3.y < this._orthoBottom)
  48825. this._orthoBottom = tempVector3.y;
  48826. if (tempVector3.x > this._orthoRight)
  48827. this._orthoRight = tempVector3.x;
  48828. if (tempVector3.y > this._orthoTop)
  48829. this._orthoTop = tempVector3.y;
  48830. }
  48831. }
  48832. }
  48833. var xOffset = this._orthoRight - this._orthoLeft;
  48834. var yOffset = this._orthoTop - this._orthoBottom;
  48835. 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);
  48836. };
  48837. DirectionalLight.prototype._buildUniformLayout = function () {
  48838. this._uniformBuffer.addUniform("vLightData", 4);
  48839. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48840. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48841. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48842. this._uniformBuffer.addUniform("depthValues", 2);
  48843. this._uniformBuffer.create();
  48844. };
  48845. /**
  48846. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48847. * @param effect The effect to update
  48848. * @param lightIndex The index of the light in the effect to update
  48849. * @returns The directional light
  48850. */
  48851. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48852. if (this.computeTransformedInformation()) {
  48853. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48854. return this;
  48855. }
  48856. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48857. return this;
  48858. };
  48859. /**
  48860. * Gets the minZ used for shadow according to both the scene and the light.
  48861. *
  48862. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48863. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48864. * @param activeCamera The camera we are returning the min for
  48865. * @returns the depth min z
  48866. */
  48867. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48868. return 1;
  48869. };
  48870. /**
  48871. * Gets the maxZ used for shadow according to both the scene and the light.
  48872. *
  48873. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48874. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48875. * @param activeCamera The camera we are returning the max for
  48876. * @returns the depth max z
  48877. */
  48878. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48879. return 1;
  48880. };
  48881. __decorate([
  48882. BABYLON.serialize()
  48883. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48884. __decorate([
  48885. BABYLON.serialize()
  48886. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48887. __decorate([
  48888. BABYLON.serialize()
  48889. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48890. return DirectionalLight;
  48891. }(BABYLON.ShadowLight));
  48892. BABYLON.DirectionalLight = DirectionalLight;
  48893. })(BABYLON || (BABYLON = {}));
  48894. //# sourceMappingURL=babylon.directionalLight.js.map
  48895. var BABYLON;
  48896. (function (BABYLON) {
  48897. /**
  48898. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48899. * These values define a cone of light starting from the position, emitting toward the direction.
  48900. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48901. * and the exponent defines the speed of the decay of the light with distance (reach).
  48902. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48903. */
  48904. var SpotLight = /** @class */ (function (_super) {
  48905. __extends(SpotLight, _super);
  48906. /**
  48907. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48908. * It can cast shadows.
  48909. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48910. * @param name The light friendly name
  48911. * @param position The position of the spot light in the scene
  48912. * @param direction The direction of the light in the scene
  48913. * @param angle The cone angle of the light in Radians
  48914. * @param exponent The light decay speed with the distance from the emission spot
  48915. * @param scene The scene the lights belongs to
  48916. */
  48917. function SpotLight(name, position, direction, angle, exponent, scene) {
  48918. var _this = _super.call(this, name, scene) || this;
  48919. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48920. _this._projectionTextureLightNear = 1e-6;
  48921. _this._projectionTextureLightFar = 1000.0;
  48922. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48923. _this._projectionTextureViewLightDirty = true;
  48924. _this._projectionTextureProjectionLightDirty = true;
  48925. _this._projectionTextureDirty = true;
  48926. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48927. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48928. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48929. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  48930. _this.position = position;
  48931. _this.direction = direction;
  48932. _this.angle = angle;
  48933. _this.exponent = exponent;
  48934. return _this;
  48935. }
  48936. Object.defineProperty(SpotLight.prototype, "angle", {
  48937. /**
  48938. * Gets the cone angle of the spot light in Radians.
  48939. */
  48940. get: function () {
  48941. return this._angle;
  48942. },
  48943. /**
  48944. * Sets the cone angle of the spot light in Radians.
  48945. */
  48946. set: function (value) {
  48947. this._angle = value;
  48948. this._projectionTextureProjectionLightDirty = true;
  48949. this.forceProjectionMatrixCompute();
  48950. },
  48951. enumerable: true,
  48952. configurable: true
  48953. });
  48954. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48955. /**
  48956. * Allows scaling the angle of the light for shadow generation only.
  48957. */
  48958. get: function () {
  48959. return this._shadowAngleScale;
  48960. },
  48961. /**
  48962. * Allows scaling the angle of the light for shadow generation only.
  48963. */
  48964. set: function (value) {
  48965. this._shadowAngleScale = value;
  48966. this.forceProjectionMatrixCompute();
  48967. },
  48968. enumerable: true,
  48969. configurable: true
  48970. });
  48971. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48972. /**
  48973. * Allows reading the projecton texture
  48974. */
  48975. get: function () {
  48976. return this._projectionTextureMatrix;
  48977. },
  48978. enumerable: true,
  48979. configurable: true
  48980. });
  48981. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48982. /**
  48983. * Gets the near clip of the Spotlight for texture projection.
  48984. */
  48985. get: function () {
  48986. return this._projectionTextureLightNear;
  48987. },
  48988. /**
  48989. * Sets the near clip of the Spotlight for texture projection.
  48990. */
  48991. set: function (value) {
  48992. this._projectionTextureLightNear = value;
  48993. this._projectionTextureProjectionLightDirty = true;
  48994. },
  48995. enumerable: true,
  48996. configurable: true
  48997. });
  48998. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48999. /**
  49000. * Gets the far clip of the Spotlight for texture projection.
  49001. */
  49002. get: function () {
  49003. return this._projectionTextureLightFar;
  49004. },
  49005. /**
  49006. * Sets the far clip of the Spotlight for texture projection.
  49007. */
  49008. set: function (value) {
  49009. this._projectionTextureLightFar = value;
  49010. this._projectionTextureProjectionLightDirty = true;
  49011. },
  49012. enumerable: true,
  49013. configurable: true
  49014. });
  49015. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49016. /**
  49017. * Gets the Up vector of the Spotlight for texture projection.
  49018. */
  49019. get: function () {
  49020. return this._projectionTextureUpDirection;
  49021. },
  49022. /**
  49023. * Sets the Up vector of the Spotlight for texture projection.
  49024. */
  49025. set: function (value) {
  49026. this._projectionTextureUpDirection = value;
  49027. this._projectionTextureProjectionLightDirty = true;
  49028. },
  49029. enumerable: true,
  49030. configurable: true
  49031. });
  49032. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49033. /**
  49034. * Gets the projection texture of the light.
  49035. */
  49036. get: function () {
  49037. return this._projectionTexture;
  49038. },
  49039. /**
  49040. * Sets the projection texture of the light.
  49041. */
  49042. set: function (value) {
  49043. this._projectionTexture = value;
  49044. this._projectionTextureDirty = true;
  49045. },
  49046. enumerable: true,
  49047. configurable: true
  49048. });
  49049. /**
  49050. * Returns the string "SpotLight".
  49051. * @returns the class name
  49052. */
  49053. SpotLight.prototype.getClassName = function () {
  49054. return "SpotLight";
  49055. };
  49056. /**
  49057. * Returns the integer 2.
  49058. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49059. */
  49060. SpotLight.prototype.getTypeID = function () {
  49061. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49062. };
  49063. /**
  49064. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49065. */
  49066. SpotLight.prototype._setDirection = function (value) {
  49067. _super.prototype._setDirection.call(this, value);
  49068. this._projectionTextureViewLightDirty = true;
  49069. };
  49070. /**
  49071. * Overrides the position setter to recompute the projection texture view light Matrix.
  49072. */
  49073. SpotLight.prototype._setPosition = function (value) {
  49074. _super.prototype._setPosition.call(this, value);
  49075. this._projectionTextureViewLightDirty = true;
  49076. };
  49077. /**
  49078. * 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.
  49079. * Returns the SpotLight.
  49080. */
  49081. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49082. var activeCamera = this.getScene().activeCamera;
  49083. if (!activeCamera) {
  49084. return;
  49085. }
  49086. this._shadowAngleScale = this._shadowAngleScale || 1;
  49087. var angle = this._shadowAngleScale * this._angle;
  49088. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49089. };
  49090. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49091. this._projectionTextureViewLightDirty = false;
  49092. this._projectionTextureDirty = true;
  49093. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49094. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49095. };
  49096. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49097. this._projectionTextureProjectionLightDirty = false;
  49098. this._projectionTextureDirty = true;
  49099. var light_far = this.projectionTextureLightFar;
  49100. var light_near = this.projectionTextureLightNear;
  49101. var P = light_far / (light_far - light_near);
  49102. var Q = -P * light_near;
  49103. var S = 1.0 / Math.tan(this._angle / 2.0);
  49104. var A = 1.0;
  49105. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  49106. };
  49107. /**
  49108. * Main function for light texture projection matrix computing.
  49109. */
  49110. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49111. this._projectionTextureDirty = false;
  49112. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49113. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49114. };
  49115. SpotLight.prototype._buildUniformLayout = function () {
  49116. this._uniformBuffer.addUniform("vLightData", 4);
  49117. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49118. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49119. this._uniformBuffer.addUniform("vLightDirection", 3);
  49120. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49121. this._uniformBuffer.addUniform("depthValues", 2);
  49122. this._uniformBuffer.create();
  49123. };
  49124. /**
  49125. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49126. * @param effect The effect to update
  49127. * @param lightIndex The index of the light in the effect to update
  49128. * @returns The spot light
  49129. */
  49130. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49131. var normalizeDirection;
  49132. if (this.computeTransformedInformation()) {
  49133. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49134. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49135. }
  49136. else {
  49137. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49138. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49139. }
  49140. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49141. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49142. if (this._projectionTextureViewLightDirty) {
  49143. this._computeProjectionTextureViewLightMatrix();
  49144. }
  49145. if (this._projectionTextureProjectionLightDirty) {
  49146. this._computeProjectionTextureProjectionLightMatrix();
  49147. }
  49148. if (this._projectionTextureDirty) {
  49149. this._computeProjectionTextureMatrix();
  49150. }
  49151. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49152. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49153. }
  49154. return this;
  49155. };
  49156. /**
  49157. * Disposes the light and the associated resources.
  49158. */
  49159. SpotLight.prototype.dispose = function () {
  49160. _super.prototype.dispose.call(this);
  49161. if (this._projectionTexture) {
  49162. this._projectionTexture.dispose();
  49163. }
  49164. };
  49165. __decorate([
  49166. BABYLON.serialize()
  49167. ], SpotLight.prototype, "angle", null);
  49168. __decorate([
  49169. BABYLON.serialize()
  49170. ], SpotLight.prototype, "shadowAngleScale", null);
  49171. __decorate([
  49172. BABYLON.serialize()
  49173. ], SpotLight.prototype, "exponent", void 0);
  49174. __decorate([
  49175. BABYLON.serialize()
  49176. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49177. __decorate([
  49178. BABYLON.serialize()
  49179. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49180. __decorate([
  49181. BABYLON.serialize()
  49182. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49183. __decorate([
  49184. BABYLON.serializeAsTexture("projectedLightTexture")
  49185. ], SpotLight.prototype, "_projectionTexture", void 0);
  49186. return SpotLight;
  49187. }(BABYLON.ShadowLight));
  49188. BABYLON.SpotLight = SpotLight;
  49189. })(BABYLON || (BABYLON = {}));
  49190. //# sourceMappingURL=babylon.spotLight.js.map
  49191. var BABYLON;
  49192. (function (BABYLON) {
  49193. /**
  49194. * Class used to override all child animations of a given target
  49195. */
  49196. var AnimationPropertiesOverride = /** @class */ (function () {
  49197. function AnimationPropertiesOverride() {
  49198. /**
  49199. * Gets or sets a value indicating if animation blending must be used
  49200. */
  49201. this.enableBlending = false;
  49202. /**
  49203. * Gets or sets the blending speed to use when enableBlending is true
  49204. */
  49205. this.blendingSpeed = 0.01;
  49206. /**
  49207. * Gets or sets the default loop mode to use
  49208. */
  49209. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49210. }
  49211. return AnimationPropertiesOverride;
  49212. }());
  49213. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49214. })(BABYLON || (BABYLON = {}));
  49215. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49216. var BABYLON;
  49217. (function (BABYLON) {
  49218. /**
  49219. * Represents the range of an animation
  49220. */
  49221. var AnimationRange = /** @class */ (function () {
  49222. /**
  49223. * Initializes the range of an animation
  49224. * @param name The name of the animation range
  49225. * @param from The starting frame of the animation
  49226. * @param to The ending frame of the animation
  49227. */
  49228. function AnimationRange(
  49229. /**The name of the animation range**/
  49230. name,
  49231. /**The starting frame of the animation */
  49232. from,
  49233. /**The ending frame of the animation*/
  49234. to) {
  49235. this.name = name;
  49236. this.from = from;
  49237. this.to = to;
  49238. }
  49239. /**
  49240. * Makes a copy of the animation range
  49241. * @returns A copy of the animation range
  49242. */
  49243. AnimationRange.prototype.clone = function () {
  49244. return new AnimationRange(this.name, this.from, this.to);
  49245. };
  49246. return AnimationRange;
  49247. }());
  49248. BABYLON.AnimationRange = AnimationRange;
  49249. /**
  49250. * Composed of a frame, and an action function
  49251. */
  49252. var AnimationEvent = /** @class */ (function () {
  49253. /**
  49254. * Initializes the animation event
  49255. * @param frame The frame for which the event is triggered
  49256. * @param action The event to perform when triggered
  49257. * @param onlyOnce Specifies if the event should be triggered only once
  49258. */
  49259. function AnimationEvent(
  49260. /** The frame for which the event is triggered **/
  49261. frame,
  49262. /** The event to perform when triggered **/
  49263. action,
  49264. /** Specifies if the event should be triggered only once**/
  49265. onlyOnce) {
  49266. this.frame = frame;
  49267. this.action = action;
  49268. this.onlyOnce = onlyOnce;
  49269. /**
  49270. * Specifies if the animation event is done
  49271. */
  49272. this.isDone = false;
  49273. }
  49274. /** @hidden */
  49275. AnimationEvent.prototype._clone = function () {
  49276. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49277. };
  49278. return AnimationEvent;
  49279. }());
  49280. BABYLON.AnimationEvent = AnimationEvent;
  49281. /**
  49282. * A cursor which tracks a point on a path
  49283. */
  49284. var PathCursor = /** @class */ (function () {
  49285. /**
  49286. * Initializes the path cursor
  49287. * @param path The path to track
  49288. */
  49289. function PathCursor(path) {
  49290. this.path = path;
  49291. /**
  49292. * Stores path cursor callbacks for when an onchange event is triggered
  49293. */
  49294. this._onchange = new Array();
  49295. /**
  49296. * The value of the path cursor
  49297. */
  49298. this.value = 0;
  49299. /**
  49300. * The animation array of the path cursor
  49301. */
  49302. this.animations = new Array();
  49303. }
  49304. /**
  49305. * Gets the cursor point on the path
  49306. * @returns A point on the path cursor at the cursor location
  49307. */
  49308. PathCursor.prototype.getPoint = function () {
  49309. var point = this.path.getPointAtLengthPosition(this.value);
  49310. return new BABYLON.Vector3(point.x, 0, point.y);
  49311. };
  49312. /**
  49313. * Moves the cursor ahead by the step amount
  49314. * @param step The amount to move the cursor forward
  49315. * @returns This path cursor
  49316. */
  49317. PathCursor.prototype.moveAhead = function (step) {
  49318. if (step === void 0) { step = 0.002; }
  49319. this.move(step);
  49320. return this;
  49321. };
  49322. /**
  49323. * Moves the cursor behind by the step amount
  49324. * @param step The amount to move the cursor back
  49325. * @returns This path cursor
  49326. */
  49327. PathCursor.prototype.moveBack = function (step) {
  49328. if (step === void 0) { step = 0.002; }
  49329. this.move(-step);
  49330. return this;
  49331. };
  49332. /**
  49333. * Moves the cursor by the step amount
  49334. * If the step amount is greater than one, an exception is thrown
  49335. * @param step The amount to move the cursor
  49336. * @returns This path cursor
  49337. */
  49338. PathCursor.prototype.move = function (step) {
  49339. if (Math.abs(step) > 1) {
  49340. throw "step size should be less than 1.";
  49341. }
  49342. this.value += step;
  49343. this.ensureLimits();
  49344. this.raiseOnChange();
  49345. return this;
  49346. };
  49347. /**
  49348. * Ensures that the value is limited between zero and one
  49349. * @returns This path cursor
  49350. */
  49351. PathCursor.prototype.ensureLimits = function () {
  49352. while (this.value > 1) {
  49353. this.value -= 1;
  49354. }
  49355. while (this.value < 0) {
  49356. this.value += 1;
  49357. }
  49358. return this;
  49359. };
  49360. /**
  49361. * Runs onchange callbacks on change (used by the animation engine)
  49362. * @returns This path cursor
  49363. */
  49364. PathCursor.prototype.raiseOnChange = function () {
  49365. var _this = this;
  49366. this._onchange.forEach(function (f) { return f(_this); });
  49367. return this;
  49368. };
  49369. /**
  49370. * Executes a function on change
  49371. * @param f A path cursor onchange callback
  49372. * @returns This path cursor
  49373. */
  49374. PathCursor.prototype.onchange = function (f) {
  49375. this._onchange.push(f);
  49376. return this;
  49377. };
  49378. return PathCursor;
  49379. }());
  49380. BABYLON.PathCursor = PathCursor;
  49381. /**
  49382. * Enum for the animation key frame interpolation type
  49383. */
  49384. var AnimationKeyInterpolation;
  49385. (function (AnimationKeyInterpolation) {
  49386. /**
  49387. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49388. */
  49389. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49390. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49391. /**
  49392. * Class used to store any kind of animation
  49393. */
  49394. var Animation = /** @class */ (function () {
  49395. /**
  49396. * Initializes the animation
  49397. * @param name Name of the animation
  49398. * @param targetProperty Property to animate
  49399. * @param framePerSecond The frames per second of the animation
  49400. * @param dataType The data type of the animation
  49401. * @param loopMode The loop mode of the animation
  49402. * @param enableBlendings Specifies if blending should be enabled
  49403. */
  49404. function Animation(
  49405. /**Name of the animation */
  49406. name,
  49407. /**Property to animate */
  49408. targetProperty,
  49409. /**The frames per second of the animation */
  49410. framePerSecond,
  49411. /**The data type of the animation */
  49412. dataType,
  49413. /**The loop mode of the animation */
  49414. loopMode,
  49415. /**Specifies if blending should be enabled */
  49416. enableBlending) {
  49417. this.name = name;
  49418. this.targetProperty = targetProperty;
  49419. this.framePerSecond = framePerSecond;
  49420. this.dataType = dataType;
  49421. this.loopMode = loopMode;
  49422. this.enableBlending = enableBlending;
  49423. /**
  49424. * @hidden Internal use only
  49425. */
  49426. this._runtimeAnimations = new Array();
  49427. /**
  49428. * The set of event that will be linked to this animation
  49429. */
  49430. this._events = new Array();
  49431. /**
  49432. * Stores the blending speed of the animation
  49433. */
  49434. this.blendingSpeed = 0.01;
  49435. /**
  49436. * Stores the animation ranges for the animation
  49437. */
  49438. this._ranges = {};
  49439. this.targetPropertyPath = targetProperty.split(".");
  49440. this.dataType = dataType;
  49441. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49442. }
  49443. /**
  49444. * @hidden Internal use
  49445. */
  49446. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49447. var dataType = undefined;
  49448. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49449. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49450. }
  49451. else if (from instanceof BABYLON.Quaternion) {
  49452. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49453. }
  49454. else if (from instanceof BABYLON.Vector3) {
  49455. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49456. }
  49457. else if (from instanceof BABYLON.Vector2) {
  49458. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49459. }
  49460. else if (from instanceof BABYLON.Color3) {
  49461. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49462. }
  49463. else if (from instanceof BABYLON.Size) {
  49464. dataType = Animation.ANIMATIONTYPE_SIZE;
  49465. }
  49466. if (dataType == undefined) {
  49467. return null;
  49468. }
  49469. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49470. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49471. animation.setKeys(keys);
  49472. if (easingFunction !== undefined) {
  49473. animation.setEasingFunction(easingFunction);
  49474. }
  49475. return animation;
  49476. };
  49477. /**
  49478. * Sets up an animation
  49479. * @param property The property to animate
  49480. * @param animationType The animation type to apply
  49481. * @param framePerSecond The frames per second of the animation
  49482. * @param easingFunction The easing function used in the animation
  49483. * @returns The created animation
  49484. */
  49485. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49486. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49487. animation.setEasingFunction(easingFunction);
  49488. return animation;
  49489. };
  49490. /**
  49491. * Create and start an animation on a node
  49492. * @param name defines the name of the global animation that will be run on all nodes
  49493. * @param node defines the root node where the animation will take place
  49494. * @param targetProperty defines property to animate
  49495. * @param framePerSecond defines the number of frame per second yo use
  49496. * @param totalFrame defines the number of frames in total
  49497. * @param from defines the initial value
  49498. * @param to defines the final value
  49499. * @param loopMode defines which loop mode you want to use (off by default)
  49500. * @param easingFunction defines the easing function to use (linear by default)
  49501. * @param onAnimationEnd defines the callback to call when animation end
  49502. * @returns the animatable created for this animation
  49503. */
  49504. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49505. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49506. if (!animation) {
  49507. return null;
  49508. }
  49509. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49510. };
  49511. /**
  49512. * Create and start an animation on a node and its descendants
  49513. * @param name defines the name of the global animation that will be run on all nodes
  49514. * @param node defines the root node where the animation will take place
  49515. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  49516. * @param targetProperty defines property to animate
  49517. * @param framePerSecond defines the number of frame per second to use
  49518. * @param totalFrame defines the number of frames in total
  49519. * @param from defines the initial value
  49520. * @param to defines the final value
  49521. * @param loopMode defines which loop mode you want to use (off by default)
  49522. * @param easingFunction defines the easing function to use (linear by default)
  49523. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49524. * @returns the list of animatables created for all nodes
  49525. * @example https://www.babylonjs-playground.com/#MH0VLI
  49526. */
  49527. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49528. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49529. if (!animation) {
  49530. return null;
  49531. }
  49532. var scene = node.getScene();
  49533. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49534. };
  49535. /**
  49536. * Creates a new animation, merges it with the existing animations and starts it
  49537. * @param name Name of the animation
  49538. * @param node Node which contains the scene that begins the animations
  49539. * @param targetProperty Specifies which property to animate
  49540. * @param framePerSecond The frames per second of the animation
  49541. * @param totalFrame The total number of frames
  49542. * @param from The frame at the beginning of the animation
  49543. * @param to The frame at the end of the animation
  49544. * @param loopMode Specifies the loop mode of the animation
  49545. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49546. * @param onAnimationEnd Callback to run once the animation is complete
  49547. * @returns Nullable animation
  49548. */
  49549. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49550. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49551. if (!animation) {
  49552. return null;
  49553. }
  49554. node.animations.push(animation);
  49555. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49556. };
  49557. /**
  49558. * Transition property of an host to the target Value
  49559. * @param property The property to transition
  49560. * @param targetValue The target Value of the property
  49561. * @param host The object where the property to animate belongs
  49562. * @param scene Scene used to run the animation
  49563. * @param frameRate Framerate (in frame/s) to use
  49564. * @param transition The transition type we want to use
  49565. * @param duration The duration of the animation, in milliseconds
  49566. * @param onAnimationEnd Callback trigger at the end of the animation
  49567. * @returns Nullable animation
  49568. */
  49569. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49570. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49571. if (duration <= 0) {
  49572. host[property] = targetValue;
  49573. if (onAnimationEnd) {
  49574. onAnimationEnd();
  49575. }
  49576. return null;
  49577. }
  49578. var endFrame = frameRate * (duration / 1000);
  49579. transition.setKeys([{
  49580. frame: 0,
  49581. value: host[property].clone ? host[property].clone() : host[property]
  49582. },
  49583. {
  49584. frame: endFrame,
  49585. value: targetValue
  49586. }]);
  49587. if (!host.animations) {
  49588. host.animations = [];
  49589. }
  49590. host.animations.push(transition);
  49591. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49592. animation.onAnimationEnd = onAnimationEnd;
  49593. return animation;
  49594. };
  49595. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49596. /**
  49597. * Return the array of runtime animations currently using this animation
  49598. */
  49599. get: function () {
  49600. return this._runtimeAnimations;
  49601. },
  49602. enumerable: true,
  49603. configurable: true
  49604. });
  49605. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49606. /**
  49607. * Specifies if any of the runtime animations are currently running
  49608. */
  49609. get: function () {
  49610. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49611. var runtimeAnimation = _a[_i];
  49612. if (!runtimeAnimation.isStopped) {
  49613. return true;
  49614. }
  49615. }
  49616. return false;
  49617. },
  49618. enumerable: true,
  49619. configurable: true
  49620. });
  49621. // Methods
  49622. /**
  49623. * Converts the animation to a string
  49624. * @param fullDetails support for multiple levels of logging within scene loading
  49625. * @returns String form of the animation
  49626. */
  49627. Animation.prototype.toString = function (fullDetails) {
  49628. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49629. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49630. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49631. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49632. if (fullDetails) {
  49633. ret += ", Ranges: {";
  49634. var first = true;
  49635. for (var name in this._ranges) {
  49636. if (first) {
  49637. ret += ", ";
  49638. first = false;
  49639. }
  49640. ret += name;
  49641. }
  49642. ret += "}";
  49643. }
  49644. return ret;
  49645. };
  49646. /**
  49647. * Add an event to this animation
  49648. * @param event Event to add
  49649. */
  49650. Animation.prototype.addEvent = function (event) {
  49651. this._events.push(event);
  49652. };
  49653. /**
  49654. * Remove all events found at the given frame
  49655. * @param frame The frame to remove events from
  49656. */
  49657. Animation.prototype.removeEvents = function (frame) {
  49658. for (var index = 0; index < this._events.length; index++) {
  49659. if (this._events[index].frame === frame) {
  49660. this._events.splice(index, 1);
  49661. index--;
  49662. }
  49663. }
  49664. };
  49665. /**
  49666. * Retrieves all the events from the animation
  49667. * @returns Events from the animation
  49668. */
  49669. Animation.prototype.getEvents = function () {
  49670. return this._events;
  49671. };
  49672. /**
  49673. * Creates an animation range
  49674. * @param name Name of the animation range
  49675. * @param from Starting frame of the animation range
  49676. * @param to Ending frame of the animation
  49677. */
  49678. Animation.prototype.createRange = function (name, from, to) {
  49679. // check name not already in use; could happen for bones after serialized
  49680. if (!this._ranges[name]) {
  49681. this._ranges[name] = new AnimationRange(name, from, to);
  49682. }
  49683. };
  49684. /**
  49685. * Deletes an animation range by name
  49686. * @param name Name of the animation range to delete
  49687. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49688. */
  49689. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49690. if (deleteFrames === void 0) { deleteFrames = true; }
  49691. var range = this._ranges[name];
  49692. if (!range) {
  49693. return;
  49694. }
  49695. if (deleteFrames) {
  49696. var from = range.from;
  49697. var to = range.to;
  49698. // this loop MUST go high to low for multiple splices to work
  49699. for (var key = this._keys.length - 1; key >= 0; key--) {
  49700. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49701. this._keys.splice(key, 1);
  49702. }
  49703. }
  49704. }
  49705. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49706. };
  49707. /**
  49708. * Gets the animation range by name, or null if not defined
  49709. * @param name Name of the animation range
  49710. * @returns Nullable animation range
  49711. */
  49712. Animation.prototype.getRange = function (name) {
  49713. return this._ranges[name];
  49714. };
  49715. /**
  49716. * Gets the key frames from the animation
  49717. * @returns The key frames of the animation
  49718. */
  49719. Animation.prototype.getKeys = function () {
  49720. return this._keys;
  49721. };
  49722. /**
  49723. * Gets the highest frame rate of the animation
  49724. * @returns Highest frame rate of the animation
  49725. */
  49726. Animation.prototype.getHighestFrame = function () {
  49727. var ret = 0;
  49728. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49729. if (ret < this._keys[key].frame) {
  49730. ret = this._keys[key].frame;
  49731. }
  49732. }
  49733. return ret;
  49734. };
  49735. /**
  49736. * Gets the easing function of the animation
  49737. * @returns Easing function of the animation
  49738. */
  49739. Animation.prototype.getEasingFunction = function () {
  49740. return this._easingFunction;
  49741. };
  49742. /**
  49743. * Sets the easing function of the animation
  49744. * @param easingFunction A custom mathematical formula for animation
  49745. */
  49746. Animation.prototype.setEasingFunction = function (easingFunction) {
  49747. this._easingFunction = easingFunction;
  49748. };
  49749. /**
  49750. * Interpolates a scalar linearly
  49751. * @param startValue Start value of the animation curve
  49752. * @param endValue End value of the animation curve
  49753. * @param gradient Scalar amount to interpolate
  49754. * @returns Interpolated scalar value
  49755. */
  49756. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49757. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49758. };
  49759. /**
  49760. * Interpolates a scalar cubically
  49761. * @param startValue Start value of the animation curve
  49762. * @param outTangent End tangent of the animation
  49763. * @param endValue End value of the animation curve
  49764. * @param inTangent Start tangent of the animation curve
  49765. * @param gradient Scalar amount to interpolate
  49766. * @returns Interpolated scalar value
  49767. */
  49768. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49769. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49770. };
  49771. /**
  49772. * Interpolates a quaternion using a spherical linear interpolation
  49773. * @param startValue Start value of the animation curve
  49774. * @param endValue End value of the animation curve
  49775. * @param gradient Scalar amount to interpolate
  49776. * @returns Interpolated quaternion value
  49777. */
  49778. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49779. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49780. };
  49781. /**
  49782. * Interpolates a quaternion cubically
  49783. * @param startValue Start value of the animation curve
  49784. * @param outTangent End tangent of the animation curve
  49785. * @param endValue End value of the animation curve
  49786. * @param inTangent Start tangent of the animation curve
  49787. * @param gradient Scalar amount to interpolate
  49788. * @returns Interpolated quaternion value
  49789. */
  49790. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49791. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49792. };
  49793. /**
  49794. * Interpolates a Vector3 linearl
  49795. * @param startValue Start value of the animation curve
  49796. * @param endValue End value of the animation curve
  49797. * @param gradient Scalar amount to interpolate
  49798. * @returns Interpolated scalar value
  49799. */
  49800. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49801. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49802. };
  49803. /**
  49804. * Interpolates a Vector3 cubically
  49805. * @param startValue Start value of the animation curve
  49806. * @param outTangent End tangent of the animation
  49807. * @param endValue End value of the animation curve
  49808. * @param inTangent Start tangent of the animation curve
  49809. * @param gradient Scalar amount to interpolate
  49810. * @returns InterpolatedVector3 value
  49811. */
  49812. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49813. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49814. };
  49815. /**
  49816. * Interpolates a Vector2 linearly
  49817. * @param startValue Start value of the animation curve
  49818. * @param endValue End value of the animation curve
  49819. * @param gradient Scalar amount to interpolate
  49820. * @returns Interpolated Vector2 value
  49821. */
  49822. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49823. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49824. };
  49825. /**
  49826. * Interpolates a Vector2 cubically
  49827. * @param startValue Start value of the animation curve
  49828. * @param outTangent End tangent of the animation
  49829. * @param endValue End value of the animation curve
  49830. * @param inTangent Start tangent of the animation curve
  49831. * @param gradient Scalar amount to interpolate
  49832. * @returns Interpolated Vector2 value
  49833. */
  49834. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49835. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49836. };
  49837. /**
  49838. * Interpolates a size linearly
  49839. * @param startValue Start value of the animation curve
  49840. * @param endValue End value of the animation curve
  49841. * @param gradient Scalar amount to interpolate
  49842. * @returns Interpolated Size value
  49843. */
  49844. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49845. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49846. };
  49847. /**
  49848. * Interpolates a Color3 linearly
  49849. * @param startValue Start value of the animation curve
  49850. * @param endValue End value of the animation curve
  49851. * @param gradient Scalar amount to interpolate
  49852. * @returns Interpolated Color3 value
  49853. */
  49854. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49855. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49856. };
  49857. /**
  49858. * @hidden Internal use only
  49859. */
  49860. Animation.prototype._getKeyValue = function (value) {
  49861. if (typeof value === "function") {
  49862. return value();
  49863. }
  49864. return value;
  49865. };
  49866. /**
  49867. * @hidden Internal use only
  49868. */
  49869. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49870. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49871. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49872. }
  49873. var keys = this.getKeys();
  49874. // Try to get a hash to find the right key
  49875. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  49876. if (keys[startKeyIndex].frame >= currentFrame) {
  49877. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49878. startKeyIndex--;
  49879. }
  49880. }
  49881. for (var key = startKeyIndex; key < keys.length; key++) {
  49882. var endKey = keys[key + 1];
  49883. if (endKey.frame >= currentFrame) {
  49884. var startKey = keys[key];
  49885. var startValue = this._getKeyValue(startKey.value);
  49886. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49887. return startValue;
  49888. }
  49889. var endValue = this._getKeyValue(endKey.value);
  49890. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49891. var frameDelta = endKey.frame - startKey.frame;
  49892. // gradient : percent of currentFrame between the frame inf and the frame sup
  49893. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49894. // check for easingFunction and correction of gradient
  49895. var easingFunction = this.getEasingFunction();
  49896. if (easingFunction != null) {
  49897. gradient = easingFunction.ease(gradient);
  49898. }
  49899. switch (this.dataType) {
  49900. // Float
  49901. case Animation.ANIMATIONTYPE_FLOAT:
  49902. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49903. switch (loopMode) {
  49904. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49905. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49906. return floatValue;
  49907. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49908. return offsetValue * repeatCount + floatValue;
  49909. }
  49910. break;
  49911. // Quaternion
  49912. case Animation.ANIMATIONTYPE_QUATERNION:
  49913. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49914. switch (loopMode) {
  49915. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49916. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49917. return quatValue;
  49918. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49919. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49920. }
  49921. return quatValue;
  49922. // Vector3
  49923. case Animation.ANIMATIONTYPE_VECTOR3:
  49924. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49925. switch (loopMode) {
  49926. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49927. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49928. return vec3Value;
  49929. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49930. return vec3Value.add(offsetValue.scale(repeatCount));
  49931. }
  49932. // Vector2
  49933. case Animation.ANIMATIONTYPE_VECTOR2:
  49934. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49935. switch (loopMode) {
  49936. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49937. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49938. return vec2Value;
  49939. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49940. return vec2Value.add(offsetValue.scale(repeatCount));
  49941. }
  49942. // Size
  49943. case Animation.ANIMATIONTYPE_SIZE:
  49944. switch (loopMode) {
  49945. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49946. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49947. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49948. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49949. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49950. }
  49951. // Color3
  49952. case Animation.ANIMATIONTYPE_COLOR3:
  49953. switch (loopMode) {
  49954. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49955. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49956. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49957. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49958. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49959. }
  49960. // Matrix
  49961. case Animation.ANIMATIONTYPE_MATRIX:
  49962. switch (loopMode) {
  49963. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49964. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49965. if (Animation.AllowMatricesInterpolation) {
  49966. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49967. }
  49968. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49969. return startValue;
  49970. }
  49971. default:
  49972. break;
  49973. }
  49974. break;
  49975. }
  49976. }
  49977. return this._getKeyValue(keys[keys.length - 1].value);
  49978. };
  49979. /**
  49980. * Defines the function to use to interpolate matrices
  49981. * @param startValue defines the start matrix
  49982. * @param endValue defines the end matrix
  49983. * @param gradient defines the gradient between both matrices
  49984. * @param result defines an optional target matrix where to store the interpolation
  49985. * @returns the interpolated matrix
  49986. */
  49987. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49988. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49989. if (result) {
  49990. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49991. return result;
  49992. }
  49993. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49994. }
  49995. if (result) {
  49996. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49997. return result;
  49998. }
  49999. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50000. };
  50001. /**
  50002. * Makes a copy of the animation
  50003. * @returns Cloned animation
  50004. */
  50005. Animation.prototype.clone = function () {
  50006. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50007. clone.enableBlending = this.enableBlending;
  50008. clone.blendingSpeed = this.blendingSpeed;
  50009. if (this._keys) {
  50010. clone.setKeys(this._keys);
  50011. }
  50012. if (this._ranges) {
  50013. clone._ranges = {};
  50014. for (var name in this._ranges) {
  50015. var range = this._ranges[name];
  50016. if (!range) {
  50017. continue;
  50018. }
  50019. clone._ranges[name] = range.clone();
  50020. }
  50021. }
  50022. return clone;
  50023. };
  50024. /**
  50025. * Sets the key frames of the animation
  50026. * @param values The animation key frames to set
  50027. */
  50028. Animation.prototype.setKeys = function (values) {
  50029. this._keys = values.slice(0);
  50030. };
  50031. /**
  50032. * Serializes the animation to an object
  50033. * @returns Serialized object
  50034. */
  50035. Animation.prototype.serialize = function () {
  50036. var serializationObject = {};
  50037. serializationObject.name = this.name;
  50038. serializationObject.property = this.targetProperty;
  50039. serializationObject.framePerSecond = this.framePerSecond;
  50040. serializationObject.dataType = this.dataType;
  50041. serializationObject.loopBehavior = this.loopMode;
  50042. serializationObject.enableBlending = this.enableBlending;
  50043. serializationObject.blendingSpeed = this.blendingSpeed;
  50044. var dataType = this.dataType;
  50045. serializationObject.keys = [];
  50046. var keys = this.getKeys();
  50047. for (var index = 0; index < keys.length; index++) {
  50048. var animationKey = keys[index];
  50049. var key = {};
  50050. key.frame = animationKey.frame;
  50051. switch (dataType) {
  50052. case Animation.ANIMATIONTYPE_FLOAT:
  50053. key.values = [animationKey.value];
  50054. break;
  50055. case Animation.ANIMATIONTYPE_QUATERNION:
  50056. case Animation.ANIMATIONTYPE_MATRIX:
  50057. case Animation.ANIMATIONTYPE_VECTOR3:
  50058. case Animation.ANIMATIONTYPE_COLOR3:
  50059. key.values = animationKey.value.asArray();
  50060. break;
  50061. }
  50062. serializationObject.keys.push(key);
  50063. }
  50064. serializationObject.ranges = [];
  50065. for (var name in this._ranges) {
  50066. var source = this._ranges[name];
  50067. if (!source) {
  50068. continue;
  50069. }
  50070. var range = {};
  50071. range.name = name;
  50072. range.from = source.from;
  50073. range.to = source.to;
  50074. serializationObject.ranges.push(range);
  50075. }
  50076. return serializationObject;
  50077. };
  50078. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50079. /**
  50080. * Get the float animation type
  50081. */
  50082. get: function () {
  50083. return Animation._ANIMATIONTYPE_FLOAT;
  50084. },
  50085. enumerable: true,
  50086. configurable: true
  50087. });
  50088. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50089. /**
  50090. * Get the Vector3 animation type
  50091. */
  50092. get: function () {
  50093. return Animation._ANIMATIONTYPE_VECTOR3;
  50094. },
  50095. enumerable: true,
  50096. configurable: true
  50097. });
  50098. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50099. /**
  50100. * Get the Vectpr2 animation type
  50101. */
  50102. get: function () {
  50103. return Animation._ANIMATIONTYPE_VECTOR2;
  50104. },
  50105. enumerable: true,
  50106. configurable: true
  50107. });
  50108. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50109. /**
  50110. * Get the Size animation type
  50111. */
  50112. get: function () {
  50113. return Animation._ANIMATIONTYPE_SIZE;
  50114. },
  50115. enumerable: true,
  50116. configurable: true
  50117. });
  50118. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50119. /**
  50120. * Get the Quaternion animation type
  50121. */
  50122. get: function () {
  50123. return Animation._ANIMATIONTYPE_QUATERNION;
  50124. },
  50125. enumerable: true,
  50126. configurable: true
  50127. });
  50128. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50129. /**
  50130. * Get the Matrix animation type
  50131. */
  50132. get: function () {
  50133. return Animation._ANIMATIONTYPE_MATRIX;
  50134. },
  50135. enumerable: true,
  50136. configurable: true
  50137. });
  50138. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50139. /**
  50140. * Get the Color3 animation type
  50141. */
  50142. get: function () {
  50143. return Animation._ANIMATIONTYPE_COLOR3;
  50144. },
  50145. enumerable: true,
  50146. configurable: true
  50147. });
  50148. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50149. /**
  50150. * Get the Relative Loop Mode
  50151. */
  50152. get: function () {
  50153. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50154. },
  50155. enumerable: true,
  50156. configurable: true
  50157. });
  50158. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50159. /**
  50160. * Get the Cycle Loop Mode
  50161. */
  50162. get: function () {
  50163. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50164. },
  50165. enumerable: true,
  50166. configurable: true
  50167. });
  50168. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50169. /**
  50170. * Get the Constant Loop Mode
  50171. */
  50172. get: function () {
  50173. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50174. },
  50175. enumerable: true,
  50176. configurable: true
  50177. });
  50178. /** @hidden */
  50179. Animation._UniversalLerp = function (left, right, amount) {
  50180. var constructor = left.constructor;
  50181. if (constructor.Lerp) { // Lerp supported
  50182. return constructor.Lerp(left, right, amount);
  50183. }
  50184. else if (constructor.Slerp) { // Slerp supported
  50185. return constructor.Slerp(left, right, amount);
  50186. }
  50187. else if (left.toFixed) { // Number
  50188. return left * (1.0 - amount) + amount * right;
  50189. }
  50190. else { // Blending not supported
  50191. return right;
  50192. }
  50193. };
  50194. /**
  50195. * Parses an animation object and creates an animation
  50196. * @param parsedAnimation Parsed animation object
  50197. * @returns Animation object
  50198. */
  50199. Animation.Parse = function (parsedAnimation) {
  50200. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50201. var dataType = parsedAnimation.dataType;
  50202. var keys = [];
  50203. var data;
  50204. var index;
  50205. if (parsedAnimation.enableBlending) {
  50206. animation.enableBlending = parsedAnimation.enableBlending;
  50207. }
  50208. if (parsedAnimation.blendingSpeed) {
  50209. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50210. }
  50211. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50212. var key = parsedAnimation.keys[index];
  50213. var inTangent;
  50214. var outTangent;
  50215. switch (dataType) {
  50216. case Animation.ANIMATIONTYPE_FLOAT:
  50217. data = key.values[0];
  50218. if (key.values.length >= 1) {
  50219. inTangent = key.values[1];
  50220. }
  50221. if (key.values.length >= 2) {
  50222. outTangent = key.values[2];
  50223. }
  50224. break;
  50225. case Animation.ANIMATIONTYPE_QUATERNION:
  50226. data = BABYLON.Quaternion.FromArray(key.values);
  50227. if (key.values.length >= 8) {
  50228. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50229. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50230. inTangent = _inTangent;
  50231. }
  50232. }
  50233. if (key.values.length >= 12) {
  50234. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50235. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50236. outTangent = _outTangent;
  50237. }
  50238. }
  50239. break;
  50240. case Animation.ANIMATIONTYPE_MATRIX:
  50241. data = BABYLON.Matrix.FromArray(key.values);
  50242. break;
  50243. case Animation.ANIMATIONTYPE_COLOR3:
  50244. data = BABYLON.Color3.FromArray(key.values);
  50245. break;
  50246. case Animation.ANIMATIONTYPE_VECTOR3:
  50247. default:
  50248. data = BABYLON.Vector3.FromArray(key.values);
  50249. break;
  50250. }
  50251. var keyData = {};
  50252. keyData.frame = key.frame;
  50253. keyData.value = data;
  50254. if (inTangent != undefined) {
  50255. keyData.inTangent = inTangent;
  50256. }
  50257. if (outTangent != undefined) {
  50258. keyData.outTangent = outTangent;
  50259. }
  50260. keys.push(keyData);
  50261. }
  50262. animation.setKeys(keys);
  50263. if (parsedAnimation.ranges) {
  50264. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50265. data = parsedAnimation.ranges[index];
  50266. animation.createRange(data.name, data.from, data.to);
  50267. }
  50268. }
  50269. return animation;
  50270. };
  50271. /**
  50272. * Appends the serialized animations from the source animations
  50273. * @param source Source containing the animations
  50274. * @param destination Target to store the animations
  50275. */
  50276. Animation.AppendSerializedAnimations = function (source, destination) {
  50277. if (source.animations) {
  50278. destination.animations = [];
  50279. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50280. var animation = source.animations[animationIndex];
  50281. destination.animations.push(animation.serialize());
  50282. }
  50283. }
  50284. };
  50285. /**
  50286. * Use matrix interpolation instead of using direct key value when animating matrices
  50287. */
  50288. Animation.AllowMatricesInterpolation = false;
  50289. /**
  50290. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50291. */
  50292. Animation.AllowMatrixDecomposeForInterpolation = true;
  50293. // Statics
  50294. /**
  50295. * Float animation type
  50296. */
  50297. Animation._ANIMATIONTYPE_FLOAT = 0;
  50298. /**
  50299. * Vector3 animation type
  50300. */
  50301. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50302. /**
  50303. * Quaternion animation type
  50304. */
  50305. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50306. /**
  50307. * Matrix animation type
  50308. */
  50309. Animation._ANIMATIONTYPE_MATRIX = 3;
  50310. /**
  50311. * Color3 animation type
  50312. */
  50313. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50314. /**
  50315. * Vector2 animation type
  50316. */
  50317. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50318. /**
  50319. * Size animation type
  50320. */
  50321. Animation._ANIMATIONTYPE_SIZE = 6;
  50322. /**
  50323. * Relative Loop Mode
  50324. */
  50325. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50326. /**
  50327. * Cycle Loop Mode
  50328. */
  50329. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50330. /**
  50331. * Constant Loop Mode
  50332. */
  50333. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50334. return Animation;
  50335. }());
  50336. BABYLON.Animation = Animation;
  50337. })(BABYLON || (BABYLON = {}));
  50338. //# sourceMappingURL=babylon.animation.js.map
  50339. var BABYLON;
  50340. (function (BABYLON) {
  50341. /**
  50342. * This class defines the direct association between an animation and a target
  50343. */
  50344. var TargetedAnimation = /** @class */ (function () {
  50345. function TargetedAnimation() {
  50346. }
  50347. return TargetedAnimation;
  50348. }());
  50349. BABYLON.TargetedAnimation = TargetedAnimation;
  50350. /**
  50351. * Use this class to create coordinated animations on multiple targets
  50352. */
  50353. var AnimationGroup = /** @class */ (function () {
  50354. function AnimationGroup(name, scene) {
  50355. if (scene === void 0) { scene = null; }
  50356. this.name = name;
  50357. this._targetedAnimations = new Array();
  50358. this._animatables = new Array();
  50359. this._from = Number.MAX_VALUE;
  50360. this._to = -Number.MAX_VALUE;
  50361. this._speedRatio = 1;
  50362. this.onAnimationEndObservable = new BABYLON.Observable();
  50363. /**
  50364. * This observable will notify when all animations have ended.
  50365. */
  50366. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50367. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50368. this._scene.animationGroups.push(this);
  50369. }
  50370. Object.defineProperty(AnimationGroup.prototype, "from", {
  50371. /**
  50372. * Gets the first frame
  50373. */
  50374. get: function () {
  50375. return this._from;
  50376. },
  50377. enumerable: true,
  50378. configurable: true
  50379. });
  50380. Object.defineProperty(AnimationGroup.prototype, "to", {
  50381. /**
  50382. * Gets the last frame
  50383. */
  50384. get: function () {
  50385. return this._to;
  50386. },
  50387. enumerable: true,
  50388. configurable: true
  50389. });
  50390. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50391. /**
  50392. * Define if the animations are started
  50393. */
  50394. get: function () {
  50395. return this._isStarted;
  50396. },
  50397. enumerable: true,
  50398. configurable: true
  50399. });
  50400. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50401. /**
  50402. * Gets or sets the speed ratio to use for all animations
  50403. */
  50404. get: function () {
  50405. return this._speedRatio;
  50406. },
  50407. /**
  50408. * Gets or sets the speed ratio to use for all animations
  50409. */
  50410. set: function (value) {
  50411. if (this._speedRatio === value) {
  50412. return;
  50413. }
  50414. this._speedRatio = value;
  50415. for (var index = 0; index < this._animatables.length; index++) {
  50416. var animatable = this._animatables[index];
  50417. animatable.speedRatio = this._speedRatio;
  50418. }
  50419. },
  50420. enumerable: true,
  50421. configurable: true
  50422. });
  50423. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50424. /**
  50425. * Gets the targeted animations for this animation group
  50426. */
  50427. get: function () {
  50428. return this._targetedAnimations;
  50429. },
  50430. enumerable: true,
  50431. configurable: true
  50432. });
  50433. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50434. /**
  50435. * returning the list of animatables controlled by this animation group.
  50436. */
  50437. get: function () {
  50438. return this._animatables;
  50439. },
  50440. enumerable: true,
  50441. configurable: true
  50442. });
  50443. /**
  50444. * Add an animation (with its target) in the group
  50445. * @param animation defines the animation we want to add
  50446. * @param target defines the target of the animation
  50447. * @returns the {BABYLON.TargetedAnimation} object
  50448. */
  50449. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50450. var targetedAnimation = {
  50451. animation: animation,
  50452. target: target
  50453. };
  50454. var keys = animation.getKeys();
  50455. if (this._from > keys[0].frame) {
  50456. this._from = keys[0].frame;
  50457. }
  50458. if (this._to < keys[keys.length - 1].frame) {
  50459. this._to = keys[keys.length - 1].frame;
  50460. }
  50461. this._targetedAnimations.push(targetedAnimation);
  50462. return targetedAnimation;
  50463. };
  50464. /**
  50465. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50466. * It can add constant keys at begin or end
  50467. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50468. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50469. */
  50470. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50471. if (beginFrame === void 0) { beginFrame = null; }
  50472. if (endFrame === void 0) { endFrame = null; }
  50473. if (beginFrame == null)
  50474. beginFrame = this._from;
  50475. if (endFrame == null)
  50476. endFrame = this._to;
  50477. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50478. var targetedAnimation = this._targetedAnimations[index];
  50479. var keys = targetedAnimation.animation.getKeys();
  50480. var startKey = keys[0];
  50481. var endKey = keys[keys.length - 1];
  50482. if (startKey.frame > beginFrame) {
  50483. var newKey = {
  50484. frame: beginFrame,
  50485. value: startKey.value,
  50486. inTangent: startKey.inTangent,
  50487. outTangent: startKey.outTangent,
  50488. interpolation: startKey.interpolation
  50489. };
  50490. keys.splice(0, 0, newKey);
  50491. }
  50492. if (endKey.frame < endFrame) {
  50493. var newKey = {
  50494. frame: endFrame,
  50495. value: endKey.value,
  50496. inTangent: endKey.outTangent,
  50497. outTangent: endKey.outTangent,
  50498. interpolation: endKey.interpolation
  50499. };
  50500. keys.push(newKey);
  50501. }
  50502. }
  50503. this._from = beginFrame;
  50504. this._to = endFrame;
  50505. return this;
  50506. };
  50507. /**
  50508. * Start all animations on given targets
  50509. * @param loop defines if animations must loop
  50510. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50511. * @param from defines the from key (optional)
  50512. * @param to defines the to key (optional)
  50513. * @returns the current animation group
  50514. */
  50515. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50516. var _this = this;
  50517. if (loop === void 0) { loop = false; }
  50518. if (speedRatio === void 0) { speedRatio = 1; }
  50519. if (this._isStarted || this._targetedAnimations.length === 0) {
  50520. return this;
  50521. }
  50522. var _loop_1 = function (targetedAnimation) {
  50523. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50524. animatable.onAnimationEnd = function () {
  50525. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50526. _this._checkAnimationGroupEnded(animatable);
  50527. };
  50528. this_1._animatables.push(animatable);
  50529. };
  50530. var this_1 = this;
  50531. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50532. var targetedAnimation = _a[_i];
  50533. _loop_1(targetedAnimation);
  50534. }
  50535. this._speedRatio = speedRatio;
  50536. this._isStarted = true;
  50537. return this;
  50538. };
  50539. /**
  50540. * Pause all animations
  50541. */
  50542. AnimationGroup.prototype.pause = function () {
  50543. if (!this._isStarted) {
  50544. return this;
  50545. }
  50546. for (var index = 0; index < this._animatables.length; index++) {
  50547. var animatable = this._animatables[index];
  50548. animatable.pause();
  50549. }
  50550. return this;
  50551. };
  50552. /**
  50553. * Play all animations to initial state
  50554. * This function will start() the animations if they were not started or will restart() them if they were paused
  50555. * @param loop defines if animations must loop
  50556. */
  50557. AnimationGroup.prototype.play = function (loop) {
  50558. // only if all animatables are ready and exist
  50559. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50560. if (loop !== undefined) {
  50561. for (var index = 0; index < this._animatables.length; index++) {
  50562. var animatable = this._animatables[index];
  50563. animatable.loopAnimation = loop;
  50564. }
  50565. }
  50566. this.restart();
  50567. }
  50568. else {
  50569. this.stop();
  50570. this.start(loop, this._speedRatio);
  50571. }
  50572. return this;
  50573. };
  50574. /**
  50575. * Reset all animations to initial state
  50576. */
  50577. AnimationGroup.prototype.reset = function () {
  50578. if (!this._isStarted) {
  50579. return this;
  50580. }
  50581. for (var index = 0; index < this._animatables.length; index++) {
  50582. var animatable = this._animatables[index];
  50583. animatable.reset();
  50584. }
  50585. return this;
  50586. };
  50587. /**
  50588. * Restart animations from key 0
  50589. */
  50590. AnimationGroup.prototype.restart = function () {
  50591. if (!this._isStarted) {
  50592. return this;
  50593. }
  50594. for (var index = 0; index < this._animatables.length; index++) {
  50595. var animatable = this._animatables[index];
  50596. animatable.restart();
  50597. }
  50598. return this;
  50599. };
  50600. /**
  50601. * Stop all animations
  50602. */
  50603. AnimationGroup.prototype.stop = function () {
  50604. if (!this._isStarted) {
  50605. return this;
  50606. }
  50607. var list = this._animatables.slice();
  50608. for (var index = 0; index < list.length; index++) {
  50609. list[index].stop();
  50610. }
  50611. this._isStarted = false;
  50612. return this;
  50613. };
  50614. /**
  50615. * Set animation weight for all animatables
  50616. * @param weight defines the weight to use
  50617. * @return the animationGroup
  50618. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50619. */
  50620. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50621. for (var index = 0; index < this._animatables.length; index++) {
  50622. var animatable = this._animatables[index];
  50623. animatable.weight = weight;
  50624. }
  50625. return this;
  50626. };
  50627. /**
  50628. * Synchronize and normalize all animatables with a source animatable
  50629. * @param root defines the root animatable to synchronize with
  50630. * @return the animationGroup
  50631. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50632. */
  50633. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50634. for (var index = 0; index < this._animatables.length; index++) {
  50635. var animatable = this._animatables[index];
  50636. animatable.syncWith(root);
  50637. }
  50638. return this;
  50639. };
  50640. /**
  50641. * Goes to a specific frame in this animation group
  50642. * @param frame the frame number to go to
  50643. * @return the animationGroup
  50644. */
  50645. AnimationGroup.prototype.goToFrame = function (frame) {
  50646. if (!this._isStarted) {
  50647. return this;
  50648. }
  50649. for (var index = 0; index < this._animatables.length; index++) {
  50650. var animatable = this._animatables[index];
  50651. animatable.goToFrame(frame);
  50652. }
  50653. return this;
  50654. };
  50655. /**
  50656. * Dispose all associated resources
  50657. */
  50658. AnimationGroup.prototype.dispose = function () {
  50659. this._targetedAnimations = [];
  50660. this._animatables = [];
  50661. var index = this._scene.animationGroups.indexOf(this);
  50662. if (index > -1) {
  50663. this._scene.animationGroups.splice(index, 1);
  50664. }
  50665. };
  50666. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50667. // animatable should be taken out of the array
  50668. var idx = this._animatables.indexOf(animatable);
  50669. if (idx > -1) {
  50670. this._animatables.splice(idx, 1);
  50671. }
  50672. // all animatables were removed? animation group ended!
  50673. if (this._animatables.length === 0) {
  50674. this._isStarted = false;
  50675. this.onAnimationGroupEndObservable.notifyObservers(this);
  50676. }
  50677. };
  50678. return AnimationGroup;
  50679. }());
  50680. BABYLON.AnimationGroup = AnimationGroup;
  50681. })(BABYLON || (BABYLON = {}));
  50682. //# sourceMappingURL=babylon.animationGroup.js.map
  50683. var BABYLON;
  50684. (function (BABYLON) {
  50685. /**
  50686. * Defines a runtime animation
  50687. */
  50688. var RuntimeAnimation = /** @class */ (function () {
  50689. /**
  50690. * Create a new RuntimeAnimation object
  50691. * @param target defines the target of the animation
  50692. * @param animation defines the source animation object
  50693. * @param scene defines the hosting scene
  50694. * @param host defines the initiating Animatable
  50695. */
  50696. function RuntimeAnimation(target, animation, scene, host) {
  50697. var _this = this;
  50698. this._events = new Array();
  50699. /**
  50700. * The current frame of the runtime animation
  50701. */
  50702. this._currentFrame = 0;
  50703. /**
  50704. * The original value of the runtime animation
  50705. */
  50706. this._originalValue = new Array();
  50707. /**
  50708. * The offsets cache of the runtime animation
  50709. */
  50710. this._offsetsCache = {};
  50711. /**
  50712. * The high limits cache of the runtime animation
  50713. */
  50714. this._highLimitsCache = {};
  50715. /**
  50716. * Specifies if the runtime animation has been stopped
  50717. */
  50718. this._stopped = false;
  50719. /**
  50720. * The blending factor of the runtime animation
  50721. */
  50722. this._blendingFactor = 0;
  50723. /**
  50724. * The target path of the runtime animation
  50725. */
  50726. this._targetPath = "";
  50727. /**
  50728. * The weight of the runtime animation
  50729. */
  50730. this._weight = 1.0;
  50731. /**
  50732. * The ratio offset of the runtime animation
  50733. */
  50734. this._ratioOffset = 0;
  50735. /**
  50736. * The previous delay of the runtime animation
  50737. */
  50738. this._previousDelay = 0;
  50739. /**
  50740. * The previous ratio of the runtime animation
  50741. */
  50742. this._previousRatio = 0;
  50743. this._animation = animation;
  50744. this._target = target;
  50745. this._scene = scene;
  50746. this._host = host;
  50747. animation._runtimeAnimations.push(this);
  50748. // Cloning events locally
  50749. var events = animation.getEvents();
  50750. if (events && events.length > 0) {
  50751. events.forEach(function (e) {
  50752. _this._events.push(e._clone());
  50753. });
  50754. }
  50755. }
  50756. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50757. /**
  50758. * Gets the current frame of the runtime animation
  50759. */
  50760. get: function () {
  50761. return this._currentFrame;
  50762. },
  50763. enumerable: true,
  50764. configurable: true
  50765. });
  50766. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50767. /**
  50768. * Gets the weight of the runtime animation
  50769. */
  50770. get: function () {
  50771. return this._weight;
  50772. },
  50773. enumerable: true,
  50774. configurable: true
  50775. });
  50776. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50777. /**
  50778. * Gets the current value of the runtime animation
  50779. */
  50780. get: function () {
  50781. return this._currentValue;
  50782. },
  50783. enumerable: true,
  50784. configurable: true
  50785. });
  50786. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50787. /**
  50788. * Gets the target path of the runtime animation
  50789. */
  50790. get: function () {
  50791. return this._targetPath;
  50792. },
  50793. enumerable: true,
  50794. configurable: true
  50795. });
  50796. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50797. /**
  50798. * Gets the actual target of the runtime animation
  50799. */
  50800. get: function () {
  50801. return this._activeTarget;
  50802. },
  50803. enumerable: true,
  50804. configurable: true
  50805. });
  50806. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50807. /**
  50808. * Gets the animation from the runtime animation
  50809. */
  50810. get: function () {
  50811. return this._animation;
  50812. },
  50813. enumerable: true,
  50814. configurable: true
  50815. });
  50816. /**
  50817. * Resets the runtime animation to the beginning
  50818. * @param restoreOriginal defines whether to restore the target property to the original value
  50819. */
  50820. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50821. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50822. if (restoreOriginal) {
  50823. if (this._target instanceof Array) {
  50824. var index = 0;
  50825. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50826. var target = _a[_i];
  50827. if (this._originalValue[index] !== undefined) {
  50828. this._setValue(target, this._originalValue[index], -1);
  50829. }
  50830. index++;
  50831. }
  50832. }
  50833. else {
  50834. if (this._originalValue[0] !== undefined) {
  50835. this._setValue(this._target, this._originalValue[0], -1);
  50836. }
  50837. }
  50838. }
  50839. this._offsetsCache = {};
  50840. this._highLimitsCache = {};
  50841. this._currentFrame = 0;
  50842. this._blendingFactor = 0;
  50843. this._originalValue = new Array();
  50844. // Events
  50845. for (var index = 0; index < this._events.length; index++) {
  50846. this._events[index].isDone = false;
  50847. }
  50848. };
  50849. /**
  50850. * Specifies if the runtime animation is stopped
  50851. * @returns Boolean specifying if the runtime animation is stopped
  50852. */
  50853. RuntimeAnimation.prototype.isStopped = function () {
  50854. return this._stopped;
  50855. };
  50856. /**
  50857. * Disposes of the runtime animation
  50858. */
  50859. RuntimeAnimation.prototype.dispose = function () {
  50860. var index = this._animation.runtimeAnimations.indexOf(this);
  50861. if (index > -1) {
  50862. this._animation.runtimeAnimations.splice(index, 1);
  50863. }
  50864. };
  50865. /**
  50866. * Interpolates the animation from the current frame
  50867. * @param currentFrame The frame to interpolate the animation to
  50868. * @param repeatCount The number of times that the animation should loop
  50869. * @param loopMode The type of looping mode to use
  50870. * @param offsetValue Animation offset value
  50871. * @param highLimitValue The high limit value
  50872. * @returns The interpolated value
  50873. */
  50874. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50875. this._currentFrame = currentFrame;
  50876. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50877. this._workValue = BABYLON.Matrix.Zero();
  50878. }
  50879. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50880. };
  50881. /**
  50882. * Apply the interpolated value to the target
  50883. * @param currentValue defines the value computed by the animation
  50884. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50885. */
  50886. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50887. if (weight === void 0) { weight = 1.0; }
  50888. if (this._target instanceof Array) {
  50889. var index = 0;
  50890. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50891. var target = _a[_i];
  50892. this._setValue(target, currentValue, weight, index);
  50893. index++;
  50894. }
  50895. }
  50896. else {
  50897. this._setValue(this._target, currentValue, weight);
  50898. }
  50899. };
  50900. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50901. if (targetIndex === void 0) { targetIndex = 0; }
  50902. // Set value
  50903. var path;
  50904. var destination;
  50905. var targetPropertyPath = this._animation.targetPropertyPath;
  50906. if (targetPropertyPath.length > 1) {
  50907. var property = target[targetPropertyPath[0]];
  50908. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50909. property = property[targetPropertyPath[index]];
  50910. }
  50911. path = targetPropertyPath[targetPropertyPath.length - 1];
  50912. destination = property;
  50913. }
  50914. else {
  50915. path = targetPropertyPath[0];
  50916. destination = target;
  50917. }
  50918. this._targetPath = path;
  50919. this._activeTarget = destination;
  50920. this._weight = weight;
  50921. if (this._originalValue[targetIndex] === undefined) {
  50922. var originalValue = void 0;
  50923. if (destination.getRestPose && path === "_matrix") { // For bones
  50924. originalValue = destination.getRestPose();
  50925. }
  50926. else {
  50927. originalValue = destination[path];
  50928. }
  50929. if (originalValue && originalValue.clone) {
  50930. this._originalValue[targetIndex] = originalValue.clone();
  50931. }
  50932. else {
  50933. this._originalValue[targetIndex] = originalValue;
  50934. }
  50935. }
  50936. // Blending
  50937. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50938. if (enableBlending && this._blendingFactor <= 1.0) {
  50939. if (!this._originalBlendValue) {
  50940. var originalValue = destination[path];
  50941. if (originalValue.clone) {
  50942. this._originalBlendValue = originalValue.clone();
  50943. }
  50944. else {
  50945. this._originalBlendValue = originalValue;
  50946. }
  50947. }
  50948. if (this._originalBlendValue.m) { // Matrix
  50949. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50950. if (this._currentValue) {
  50951. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50952. }
  50953. else {
  50954. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50955. }
  50956. }
  50957. else {
  50958. if (this._currentValue) {
  50959. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50960. }
  50961. else {
  50962. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50963. }
  50964. }
  50965. }
  50966. else {
  50967. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50968. }
  50969. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50970. this._blendingFactor += blendingSpeed;
  50971. }
  50972. else {
  50973. this._currentValue = currentValue;
  50974. }
  50975. if (weight !== -1.0) {
  50976. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50977. }
  50978. else {
  50979. destination[path] = this._currentValue;
  50980. }
  50981. if (target.markAsDirty) {
  50982. target.markAsDirty(this._animation.targetProperty);
  50983. }
  50984. };
  50985. /**
  50986. * Gets the loop pmode of the runtime animation
  50987. * @returns Loop Mode
  50988. */
  50989. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50990. if (this._target && this._target.animationPropertiesOverride) {
  50991. return this._target.animationPropertiesOverride.loopMode;
  50992. }
  50993. return this._animation.loopMode;
  50994. };
  50995. /**
  50996. * Move the current animation to a given frame
  50997. * @param frame defines the frame to move to
  50998. */
  50999. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51000. var keys = this._animation.getKeys();
  51001. if (frame < keys[0].frame) {
  51002. frame = keys[0].frame;
  51003. }
  51004. else if (frame > keys[keys.length - 1].frame) {
  51005. frame = keys[keys.length - 1].frame;
  51006. }
  51007. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51008. this.setValue(currentValue, -1);
  51009. };
  51010. /**
  51011. * @hidden Internal use only
  51012. */
  51013. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51014. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51015. this._ratioOffset = this._previousRatio - newRatio;
  51016. };
  51017. /**
  51018. * Execute the current animation
  51019. * @param delay defines the delay to add to the current frame
  51020. * @param from defines the lower bound of the animation range
  51021. * @param to defines the upper bound of the animation range
  51022. * @param loop defines if the current animation must loop
  51023. * @param speedRatio defines the current speed ratio
  51024. * @param weight defines the weight of the animation (default is -1 so no weight)
  51025. * @returns a boolean indicating if the animation has ended
  51026. */
  51027. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51028. if (weight === void 0) { weight = -1.0; }
  51029. var targetPropertyPath = this._animation.targetPropertyPath;
  51030. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51031. this._stopped = true;
  51032. return false;
  51033. }
  51034. var keys = this._animation.getKeys();
  51035. // Return immediately if there is only one key frame.
  51036. if (keys.length === 1) {
  51037. this.setValue(keys[0].value, weight);
  51038. return !loop;
  51039. }
  51040. var returnValue = true;
  51041. // Adding a start key at frame 0 if missing
  51042. if (keys[0].frame !== 0) {
  51043. var newKey = { frame: 0, value: keys[0].value };
  51044. keys.splice(0, 0, newKey);
  51045. }
  51046. // Check limits
  51047. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51048. from = keys[0].frame;
  51049. }
  51050. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51051. to = keys[keys.length - 1].frame;
  51052. }
  51053. //to and from cannot be the same key
  51054. if (from === to) {
  51055. if (from > keys[0].frame) {
  51056. from--;
  51057. }
  51058. else if (to < keys[keys.length - 1].frame) {
  51059. to++;
  51060. }
  51061. }
  51062. // Compute ratio
  51063. var range = to - from;
  51064. var offsetValue;
  51065. // ratio represents the frame delta between from and to
  51066. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51067. var highLimitValue = 0;
  51068. this._previousDelay = delay;
  51069. this._previousRatio = ratio;
  51070. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51071. returnValue = false;
  51072. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51073. }
  51074. else {
  51075. // Get max value if required
  51076. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51077. var keyOffset = to.toString() + from.toString();
  51078. if (!this._offsetsCache[keyOffset]) {
  51079. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51080. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51081. switch (this._animation.dataType) {
  51082. // Float
  51083. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51084. this._offsetsCache[keyOffset] = toValue - fromValue;
  51085. break;
  51086. // Quaternion
  51087. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51088. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51089. break;
  51090. // Vector3
  51091. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51092. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51093. // Vector2
  51094. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51095. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51096. // Size
  51097. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51098. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51099. // Color3
  51100. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51101. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51102. default:
  51103. break;
  51104. }
  51105. this._highLimitsCache[keyOffset] = toValue;
  51106. }
  51107. highLimitValue = this._highLimitsCache[keyOffset];
  51108. offsetValue = this._offsetsCache[keyOffset];
  51109. }
  51110. }
  51111. if (offsetValue === undefined) {
  51112. switch (this._animation.dataType) {
  51113. // Float
  51114. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51115. offsetValue = 0;
  51116. break;
  51117. // Quaternion
  51118. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51119. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51120. break;
  51121. // Vector3
  51122. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51123. offsetValue = BABYLON.Vector3.Zero();
  51124. break;
  51125. // Vector2
  51126. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51127. offsetValue = BABYLON.Vector2.Zero();
  51128. break;
  51129. // Size
  51130. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51131. offsetValue = BABYLON.Size.Zero();
  51132. break;
  51133. // Color3
  51134. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51135. offsetValue = BABYLON.Color3.Black();
  51136. }
  51137. }
  51138. // Compute value
  51139. var repeatCount = (ratio / range) >> 0;
  51140. var currentFrame = returnValue ? from + ratio % range : to;
  51141. // Need to normalize?
  51142. if (this._host && this._host.syncRoot) {
  51143. var syncRoot = this._host.syncRoot;
  51144. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51145. currentFrame = from + (to - from) * hostNormalizedFrame;
  51146. }
  51147. // Reset events if looping
  51148. var events = this._events;
  51149. if (range > 0 && this.currentFrame > currentFrame ||
  51150. range < 0 && this.currentFrame < currentFrame) {
  51151. // Need to reset animation events
  51152. for (var index = 0; index < events.length; index++) {
  51153. if (!events[index].onlyOnce) {
  51154. // reset event, the animation is looping
  51155. events[index].isDone = false;
  51156. }
  51157. }
  51158. }
  51159. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51160. // Set value
  51161. this.setValue(currentValue, weight);
  51162. // Check events
  51163. for (var index = 0; index < events.length; index++) {
  51164. // Make sure current frame has passed event frame and that event frame is within the current range
  51165. // Also, handle both forward and reverse animations
  51166. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51167. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51168. var event = events[index];
  51169. if (!event.isDone) {
  51170. // If event should be done only once, remove it.
  51171. if (event.onlyOnce) {
  51172. events.splice(index, 1);
  51173. index--;
  51174. }
  51175. event.isDone = true;
  51176. event.action();
  51177. } // Don't do anything if the event has already be done.
  51178. }
  51179. }
  51180. if (!returnValue) {
  51181. this._stopped = true;
  51182. }
  51183. return returnValue;
  51184. };
  51185. return RuntimeAnimation;
  51186. }());
  51187. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51188. })(BABYLON || (BABYLON = {}));
  51189. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51190. var BABYLON;
  51191. (function (BABYLON) {
  51192. /**
  51193. * Class used to store an actual running animation
  51194. */
  51195. var Animatable = /** @class */ (function () {
  51196. /**
  51197. * Creates a new Animatable
  51198. * @param scene defines the hosting scene
  51199. * @param target defines the target object
  51200. * @param fromFrame defines the starting frame number (default is 0)
  51201. * @param toFrame defines the ending frame number (default is 100)
  51202. * @param loopAnimation defines if the animation must loop (default is false)
  51203. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51204. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51205. * @param animations defines a group of animation to add to the new Animatable
  51206. */
  51207. function Animatable(scene,
  51208. /** defines the target object */
  51209. target,
  51210. /** defines the starting frame number (default is 0) */
  51211. fromFrame,
  51212. /** defines the ending frame number (default is 100) */
  51213. toFrame,
  51214. /** defines if the animation must loop (default is false) */
  51215. loopAnimation, speedRatio,
  51216. /** defines a callback to call when animation ends if it is not looping */
  51217. onAnimationEnd, animations) {
  51218. if (fromFrame === void 0) { fromFrame = 0; }
  51219. if (toFrame === void 0) { toFrame = 100; }
  51220. if (loopAnimation === void 0) { loopAnimation = false; }
  51221. if (speedRatio === void 0) { speedRatio = 1.0; }
  51222. this.target = target;
  51223. this.fromFrame = fromFrame;
  51224. this.toFrame = toFrame;
  51225. this.loopAnimation = loopAnimation;
  51226. this.onAnimationEnd = onAnimationEnd;
  51227. this._localDelayOffset = null;
  51228. this._pausedDelay = null;
  51229. this._runtimeAnimations = new Array();
  51230. this._paused = false;
  51231. this._speedRatio = 1;
  51232. this._weight = -1.0;
  51233. /**
  51234. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51235. * This will only apply for non looping animation (default is true)
  51236. */
  51237. this.disposeOnEnd = true;
  51238. /**
  51239. * Gets a boolean indicating if the animation has started
  51240. */
  51241. this.animationStarted = false;
  51242. /**
  51243. * Observer raised when the animation ends
  51244. */
  51245. this.onAnimationEndObservable = new BABYLON.Observable();
  51246. this._scene = scene;
  51247. if (animations) {
  51248. this.appendAnimations(target, animations);
  51249. }
  51250. this._speedRatio = speedRatio;
  51251. scene._activeAnimatables.push(this);
  51252. }
  51253. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51254. /**
  51255. * Gets the root Animatable used to synchronize and normalize animations
  51256. */
  51257. get: function () {
  51258. return this._syncRoot;
  51259. },
  51260. enumerable: true,
  51261. configurable: true
  51262. });
  51263. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51264. /**
  51265. * Gets the current frame of the first RuntimeAnimation
  51266. * Used to synchronize Animatables
  51267. */
  51268. get: function () {
  51269. if (this._runtimeAnimations.length === 0) {
  51270. return 0;
  51271. }
  51272. return this._runtimeAnimations[0].currentFrame;
  51273. },
  51274. enumerable: true,
  51275. configurable: true
  51276. });
  51277. Object.defineProperty(Animatable.prototype, "weight", {
  51278. /**
  51279. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51280. */
  51281. get: function () {
  51282. return this._weight;
  51283. },
  51284. set: function (value) {
  51285. if (value === -1) { // -1 is ok and means no weight
  51286. this._weight = -1;
  51287. return;
  51288. }
  51289. // Else weight must be in [0, 1] range
  51290. this._weight = Math.min(Math.max(value, 0), 1.0);
  51291. },
  51292. enumerable: true,
  51293. configurable: true
  51294. });
  51295. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51296. /**
  51297. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51298. */
  51299. get: function () {
  51300. return this._speedRatio;
  51301. },
  51302. set: function (value) {
  51303. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51304. var animation = this._runtimeAnimations[index];
  51305. animation._prepareForSpeedRatioChange(value);
  51306. }
  51307. this._speedRatio = value;
  51308. },
  51309. enumerable: true,
  51310. configurable: true
  51311. });
  51312. // Methods
  51313. /**
  51314. * Synchronize and normalize current Animatable with a source Animatable
  51315. * This is useful when using animation weights and when animations are not of the same length
  51316. * @param root defines the root Animatable to synchronize with
  51317. * @returns the current Animatable
  51318. */
  51319. Animatable.prototype.syncWith = function (root) {
  51320. this._syncRoot = root;
  51321. if (root) {
  51322. // Make sure this animatable will animate after the root
  51323. var index = this._scene._activeAnimatables.indexOf(this);
  51324. if (index > -1) {
  51325. this._scene._activeAnimatables.splice(index, 1);
  51326. this._scene._activeAnimatables.push(this);
  51327. }
  51328. }
  51329. return this;
  51330. };
  51331. /**
  51332. * Gets the list of runtime animations
  51333. * @returns an array of RuntimeAnimation
  51334. */
  51335. Animatable.prototype.getAnimations = function () {
  51336. return this._runtimeAnimations;
  51337. };
  51338. /**
  51339. * Adds more animations to the current animatable
  51340. * @param target defines the target of the animations
  51341. * @param animations defines the new animations to add
  51342. */
  51343. Animatable.prototype.appendAnimations = function (target, animations) {
  51344. for (var index = 0; index < animations.length; index++) {
  51345. var animation = animations[index];
  51346. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51347. }
  51348. };
  51349. /**
  51350. * Gets the source animation for a specific property
  51351. * @param property defines the propertyu to look for
  51352. * @returns null or the source animation for the given property
  51353. */
  51354. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51355. var runtimeAnimations = this._runtimeAnimations;
  51356. for (var index = 0; index < runtimeAnimations.length; index++) {
  51357. if (runtimeAnimations[index].animation.targetProperty === property) {
  51358. return runtimeAnimations[index].animation;
  51359. }
  51360. }
  51361. return null;
  51362. };
  51363. /**
  51364. * Gets the runtime animation for a specific property
  51365. * @param property defines the propertyu to look for
  51366. * @returns null or the runtime animation for the given property
  51367. */
  51368. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51369. var runtimeAnimations = this._runtimeAnimations;
  51370. for (var index = 0; index < runtimeAnimations.length; index++) {
  51371. if (runtimeAnimations[index].animation.targetProperty === property) {
  51372. return runtimeAnimations[index];
  51373. }
  51374. }
  51375. return null;
  51376. };
  51377. /**
  51378. * Resets the animatable to its original state
  51379. */
  51380. Animatable.prototype.reset = function () {
  51381. var runtimeAnimations = this._runtimeAnimations;
  51382. for (var index = 0; index < runtimeAnimations.length; index++) {
  51383. runtimeAnimations[index].reset(true);
  51384. }
  51385. this._localDelayOffset = null;
  51386. this._pausedDelay = null;
  51387. };
  51388. /**
  51389. * Allows the animatable to blend with current running animations
  51390. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51391. * @param blendingSpeed defines the blending speed to use
  51392. */
  51393. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51394. var runtimeAnimations = this._runtimeAnimations;
  51395. for (var index = 0; index < runtimeAnimations.length; index++) {
  51396. runtimeAnimations[index].animation.enableBlending = true;
  51397. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51398. }
  51399. };
  51400. /**
  51401. * Disable animation blending
  51402. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51403. */
  51404. Animatable.prototype.disableBlending = function () {
  51405. var runtimeAnimations = this._runtimeAnimations;
  51406. for (var index = 0; index < runtimeAnimations.length; index++) {
  51407. runtimeAnimations[index].animation.enableBlending = false;
  51408. }
  51409. };
  51410. /**
  51411. * Jump directly to a given frame
  51412. * @param frame defines the frame to jump to
  51413. */
  51414. Animatable.prototype.goToFrame = function (frame) {
  51415. var runtimeAnimations = this._runtimeAnimations;
  51416. if (runtimeAnimations[0]) {
  51417. var fps = runtimeAnimations[0].animation.framePerSecond;
  51418. var currentFrame = runtimeAnimations[0].currentFrame;
  51419. var adjustTime = frame - currentFrame;
  51420. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51421. if (this._localDelayOffset === null) {
  51422. this._localDelayOffset = 0;
  51423. }
  51424. this._localDelayOffset -= delay;
  51425. }
  51426. for (var index = 0; index < runtimeAnimations.length; index++) {
  51427. runtimeAnimations[index].goToFrame(frame);
  51428. }
  51429. };
  51430. /**
  51431. * Pause the animation
  51432. */
  51433. Animatable.prototype.pause = function () {
  51434. if (this._paused) {
  51435. return;
  51436. }
  51437. this._paused = true;
  51438. };
  51439. /**
  51440. * Restart the animation
  51441. */
  51442. Animatable.prototype.restart = function () {
  51443. this._paused = false;
  51444. };
  51445. Animatable.prototype._raiseOnAnimationEnd = function () {
  51446. if (this.onAnimationEnd) {
  51447. this.onAnimationEnd();
  51448. }
  51449. this.onAnimationEndObservable.notifyObservers(this);
  51450. };
  51451. /**
  51452. * Stop and delete the current animation
  51453. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51454. */
  51455. Animatable.prototype.stop = function (animationName) {
  51456. if (animationName) {
  51457. var idx = this._scene._activeAnimatables.indexOf(this);
  51458. if (idx > -1) {
  51459. var runtimeAnimations = this._runtimeAnimations;
  51460. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51461. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51462. continue;
  51463. }
  51464. runtimeAnimations[index].dispose();
  51465. runtimeAnimations.splice(index, 1);
  51466. }
  51467. if (runtimeAnimations.length == 0) {
  51468. this._scene._activeAnimatables.splice(idx, 1);
  51469. this._raiseOnAnimationEnd();
  51470. }
  51471. }
  51472. }
  51473. else {
  51474. var index = this._scene._activeAnimatables.indexOf(this);
  51475. if (index > -1) {
  51476. this._scene._activeAnimatables.splice(index, 1);
  51477. var runtimeAnimations = this._runtimeAnimations;
  51478. for (var index = 0; index < runtimeAnimations.length; index++) {
  51479. runtimeAnimations[index].dispose();
  51480. }
  51481. this._raiseOnAnimationEnd();
  51482. }
  51483. }
  51484. };
  51485. /**
  51486. * Wait asynchronously for the animation to end
  51487. * @returns a promise which will be fullfilled when the animation ends
  51488. */
  51489. Animatable.prototype.waitAsync = function () {
  51490. var _this = this;
  51491. return new Promise(function (resolve, reject) {
  51492. _this.onAnimationEndObservable.add(function () {
  51493. resolve(_this);
  51494. }, undefined, undefined, _this, true);
  51495. });
  51496. };
  51497. /** @hidden */
  51498. Animatable.prototype._animate = function (delay) {
  51499. if (this._paused) {
  51500. this.animationStarted = false;
  51501. if (this._pausedDelay === null) {
  51502. this._pausedDelay = delay;
  51503. }
  51504. return true;
  51505. }
  51506. if (this._localDelayOffset === null) {
  51507. this._localDelayOffset = delay;
  51508. this._pausedDelay = null;
  51509. }
  51510. else if (this._pausedDelay !== null) {
  51511. this._localDelayOffset += delay - this._pausedDelay;
  51512. this._pausedDelay = null;
  51513. }
  51514. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51515. return true;
  51516. }
  51517. // Animating
  51518. var running = false;
  51519. var runtimeAnimations = this._runtimeAnimations;
  51520. var index;
  51521. for (index = 0; index < runtimeAnimations.length; index++) {
  51522. var animation = runtimeAnimations[index];
  51523. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51524. running = running || isRunning;
  51525. }
  51526. this.animationStarted = running;
  51527. if (!running) {
  51528. if (this.disposeOnEnd) {
  51529. // Remove from active animatables
  51530. index = this._scene._activeAnimatables.indexOf(this);
  51531. this._scene._activeAnimatables.splice(index, 1);
  51532. // Dispose all runtime animations
  51533. for (index = 0; index < runtimeAnimations.length; index++) {
  51534. runtimeAnimations[index].dispose();
  51535. }
  51536. }
  51537. this._raiseOnAnimationEnd();
  51538. if (this.disposeOnEnd) {
  51539. this.onAnimationEnd = null;
  51540. this.onAnimationEndObservable.clear();
  51541. }
  51542. }
  51543. return running;
  51544. };
  51545. return Animatable;
  51546. }());
  51547. BABYLON.Animatable = Animatable;
  51548. })(BABYLON || (BABYLON = {}));
  51549. //# sourceMappingURL=babylon.animatable.js.map
  51550. var BABYLON;
  51551. (function (BABYLON) {
  51552. var EasingFunction = /** @class */ (function () {
  51553. function EasingFunction() {
  51554. // Properties
  51555. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51556. }
  51557. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51558. get: function () {
  51559. return EasingFunction._EASINGMODE_EASEIN;
  51560. },
  51561. enumerable: true,
  51562. configurable: true
  51563. });
  51564. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51565. get: function () {
  51566. return EasingFunction._EASINGMODE_EASEOUT;
  51567. },
  51568. enumerable: true,
  51569. configurable: true
  51570. });
  51571. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51572. get: function () {
  51573. return EasingFunction._EASINGMODE_EASEINOUT;
  51574. },
  51575. enumerable: true,
  51576. configurable: true
  51577. });
  51578. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51579. var n = Math.min(Math.max(easingMode, 0), 2);
  51580. this._easingMode = n;
  51581. };
  51582. EasingFunction.prototype.getEasingMode = function () {
  51583. return this._easingMode;
  51584. };
  51585. EasingFunction.prototype.easeInCore = function (gradient) {
  51586. throw new Error('You must implement this method');
  51587. };
  51588. EasingFunction.prototype.ease = function (gradient) {
  51589. switch (this._easingMode) {
  51590. case EasingFunction.EASINGMODE_EASEIN:
  51591. return this.easeInCore(gradient);
  51592. case EasingFunction.EASINGMODE_EASEOUT:
  51593. return (1 - this.easeInCore(1 - gradient));
  51594. }
  51595. if (gradient >= 0.5) {
  51596. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51597. }
  51598. return (this.easeInCore(gradient * 2) * 0.5);
  51599. };
  51600. //Statics
  51601. EasingFunction._EASINGMODE_EASEIN = 0;
  51602. EasingFunction._EASINGMODE_EASEOUT = 1;
  51603. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51604. return EasingFunction;
  51605. }());
  51606. BABYLON.EasingFunction = EasingFunction;
  51607. var CircleEase = /** @class */ (function (_super) {
  51608. __extends(CircleEase, _super);
  51609. function CircleEase() {
  51610. return _super !== null && _super.apply(this, arguments) || this;
  51611. }
  51612. CircleEase.prototype.easeInCore = function (gradient) {
  51613. gradient = Math.max(0, Math.min(1, gradient));
  51614. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51615. };
  51616. return CircleEase;
  51617. }(EasingFunction));
  51618. BABYLON.CircleEase = CircleEase;
  51619. var BackEase = /** @class */ (function (_super) {
  51620. __extends(BackEase, _super);
  51621. function BackEase(amplitude) {
  51622. if (amplitude === void 0) { amplitude = 1; }
  51623. var _this = _super.call(this) || this;
  51624. _this.amplitude = amplitude;
  51625. return _this;
  51626. }
  51627. BackEase.prototype.easeInCore = function (gradient) {
  51628. var num = Math.max(0, this.amplitude);
  51629. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51630. };
  51631. return BackEase;
  51632. }(EasingFunction));
  51633. BABYLON.BackEase = BackEase;
  51634. var BounceEase = /** @class */ (function (_super) {
  51635. __extends(BounceEase, _super);
  51636. function BounceEase(bounces, bounciness) {
  51637. if (bounces === void 0) { bounces = 3; }
  51638. if (bounciness === void 0) { bounciness = 2; }
  51639. var _this = _super.call(this) || this;
  51640. _this.bounces = bounces;
  51641. _this.bounciness = bounciness;
  51642. return _this;
  51643. }
  51644. BounceEase.prototype.easeInCore = function (gradient) {
  51645. var y = Math.max(0.0, this.bounces);
  51646. var bounciness = this.bounciness;
  51647. if (bounciness <= 1.0) {
  51648. bounciness = 1.001;
  51649. }
  51650. var num9 = Math.pow(bounciness, y);
  51651. var num5 = 1.0 - bounciness;
  51652. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51653. var num15 = gradient * num4;
  51654. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51655. var num3 = Math.floor(num65);
  51656. var num13 = num3 + 1.0;
  51657. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51658. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51659. var num7 = (num8 + num12) * 0.5;
  51660. var num6 = gradient - num7;
  51661. var num2 = num7 - num8;
  51662. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51663. };
  51664. return BounceEase;
  51665. }(EasingFunction));
  51666. BABYLON.BounceEase = BounceEase;
  51667. var CubicEase = /** @class */ (function (_super) {
  51668. __extends(CubicEase, _super);
  51669. function CubicEase() {
  51670. return _super !== null && _super.apply(this, arguments) || this;
  51671. }
  51672. CubicEase.prototype.easeInCore = function (gradient) {
  51673. return (gradient * gradient * gradient);
  51674. };
  51675. return CubicEase;
  51676. }(EasingFunction));
  51677. BABYLON.CubicEase = CubicEase;
  51678. var ElasticEase = /** @class */ (function (_super) {
  51679. __extends(ElasticEase, _super);
  51680. function ElasticEase(oscillations, springiness) {
  51681. if (oscillations === void 0) { oscillations = 3; }
  51682. if (springiness === void 0) { springiness = 3; }
  51683. var _this = _super.call(this) || this;
  51684. _this.oscillations = oscillations;
  51685. _this.springiness = springiness;
  51686. return _this;
  51687. }
  51688. ElasticEase.prototype.easeInCore = function (gradient) {
  51689. var num2;
  51690. var num3 = Math.max(0.0, this.oscillations);
  51691. var num = Math.max(0.0, this.springiness);
  51692. if (num == 0) {
  51693. num2 = gradient;
  51694. }
  51695. else {
  51696. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51697. }
  51698. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51699. };
  51700. return ElasticEase;
  51701. }(EasingFunction));
  51702. BABYLON.ElasticEase = ElasticEase;
  51703. var ExponentialEase = /** @class */ (function (_super) {
  51704. __extends(ExponentialEase, _super);
  51705. function ExponentialEase(exponent) {
  51706. if (exponent === void 0) { exponent = 2; }
  51707. var _this = _super.call(this) || this;
  51708. _this.exponent = exponent;
  51709. return _this;
  51710. }
  51711. ExponentialEase.prototype.easeInCore = function (gradient) {
  51712. if (this.exponent <= 0) {
  51713. return gradient;
  51714. }
  51715. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51716. };
  51717. return ExponentialEase;
  51718. }(EasingFunction));
  51719. BABYLON.ExponentialEase = ExponentialEase;
  51720. var PowerEase = /** @class */ (function (_super) {
  51721. __extends(PowerEase, _super);
  51722. function PowerEase(power) {
  51723. if (power === void 0) { power = 2; }
  51724. var _this = _super.call(this) || this;
  51725. _this.power = power;
  51726. return _this;
  51727. }
  51728. PowerEase.prototype.easeInCore = function (gradient) {
  51729. var y = Math.max(0.0, this.power);
  51730. return Math.pow(gradient, y);
  51731. };
  51732. return PowerEase;
  51733. }(EasingFunction));
  51734. BABYLON.PowerEase = PowerEase;
  51735. var QuadraticEase = /** @class */ (function (_super) {
  51736. __extends(QuadraticEase, _super);
  51737. function QuadraticEase() {
  51738. return _super !== null && _super.apply(this, arguments) || this;
  51739. }
  51740. QuadraticEase.prototype.easeInCore = function (gradient) {
  51741. return (gradient * gradient);
  51742. };
  51743. return QuadraticEase;
  51744. }(EasingFunction));
  51745. BABYLON.QuadraticEase = QuadraticEase;
  51746. var QuarticEase = /** @class */ (function (_super) {
  51747. __extends(QuarticEase, _super);
  51748. function QuarticEase() {
  51749. return _super !== null && _super.apply(this, arguments) || this;
  51750. }
  51751. QuarticEase.prototype.easeInCore = function (gradient) {
  51752. return (gradient * gradient * gradient * gradient);
  51753. };
  51754. return QuarticEase;
  51755. }(EasingFunction));
  51756. BABYLON.QuarticEase = QuarticEase;
  51757. var QuinticEase = /** @class */ (function (_super) {
  51758. __extends(QuinticEase, _super);
  51759. function QuinticEase() {
  51760. return _super !== null && _super.apply(this, arguments) || this;
  51761. }
  51762. QuinticEase.prototype.easeInCore = function (gradient) {
  51763. return (gradient * gradient * gradient * gradient * gradient);
  51764. };
  51765. return QuinticEase;
  51766. }(EasingFunction));
  51767. BABYLON.QuinticEase = QuinticEase;
  51768. var SineEase = /** @class */ (function (_super) {
  51769. __extends(SineEase, _super);
  51770. function SineEase() {
  51771. return _super !== null && _super.apply(this, arguments) || this;
  51772. }
  51773. SineEase.prototype.easeInCore = function (gradient) {
  51774. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51775. };
  51776. return SineEase;
  51777. }(EasingFunction));
  51778. BABYLON.SineEase = SineEase;
  51779. var BezierCurveEase = /** @class */ (function (_super) {
  51780. __extends(BezierCurveEase, _super);
  51781. function BezierCurveEase(x1, y1, x2, y2) {
  51782. if (x1 === void 0) { x1 = 0; }
  51783. if (y1 === void 0) { y1 = 0; }
  51784. if (x2 === void 0) { x2 = 1; }
  51785. if (y2 === void 0) { y2 = 1; }
  51786. var _this = _super.call(this) || this;
  51787. _this.x1 = x1;
  51788. _this.y1 = y1;
  51789. _this.x2 = x2;
  51790. _this.y2 = y2;
  51791. return _this;
  51792. }
  51793. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51794. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51795. };
  51796. return BezierCurveEase;
  51797. }(EasingFunction));
  51798. BABYLON.BezierCurveEase = BezierCurveEase;
  51799. })(BABYLON || (BABYLON = {}));
  51800. //# sourceMappingURL=babylon.easing.js.map
  51801. var BABYLON;
  51802. (function (BABYLON) {
  51803. /**
  51804. * A Condition applied to an Action
  51805. */
  51806. var Condition = /** @class */ (function () {
  51807. /**
  51808. * Creates a new Condition
  51809. * @param actionManager the manager of the action the condition is applied to
  51810. */
  51811. function Condition(actionManager) {
  51812. this._actionManager = actionManager;
  51813. }
  51814. /**
  51815. * Check if the current condition is valid
  51816. * @returns a boolean
  51817. */
  51818. Condition.prototype.isValid = function () {
  51819. return true;
  51820. };
  51821. /**
  51822. * Internal only
  51823. * @hidden
  51824. */
  51825. Condition.prototype._getProperty = function (propertyPath) {
  51826. return this._actionManager._getProperty(propertyPath);
  51827. };
  51828. /**
  51829. * Internal only
  51830. * @hidden
  51831. */
  51832. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51833. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51834. };
  51835. /**
  51836. * Serialize placeholder for child classes
  51837. * @returns the serialized object
  51838. */
  51839. Condition.prototype.serialize = function () {
  51840. };
  51841. /**
  51842. * Internal only
  51843. * @hidden
  51844. */
  51845. Condition.prototype._serialize = function (serializedCondition) {
  51846. return {
  51847. type: 2,
  51848. children: [],
  51849. name: serializedCondition.name,
  51850. properties: serializedCondition.properties
  51851. };
  51852. };
  51853. return Condition;
  51854. }());
  51855. BABYLON.Condition = Condition;
  51856. /**
  51857. * Defines specific conditional operators as extensions of Condition
  51858. */
  51859. var ValueCondition = /** @class */ (function (_super) {
  51860. __extends(ValueCondition, _super);
  51861. /**
  51862. * Creates a new ValueCondition
  51863. * @param actionManager manager for the action the condition applies to
  51864. * @param target for the action
  51865. * @param propertyPath path to specify the property of the target the conditional operator uses
  51866. * @param value the value compared by the conditional operator against the current value of the property
  51867. * @param operator the conditional operator, default ValueCondition.IsEqual
  51868. */
  51869. function ValueCondition(actionManager, target,
  51870. /** path to specify the property of the target the conditional operator uses */
  51871. propertyPath,
  51872. /** the value compared by the conditional operator against the current value of the property */
  51873. value,
  51874. /** the conditional operator, default ValueCondition.IsEqual */
  51875. operator) {
  51876. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51877. var _this = _super.call(this, actionManager) || this;
  51878. _this.propertyPath = propertyPath;
  51879. _this.value = value;
  51880. _this.operator = operator;
  51881. _this._target = target;
  51882. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51883. _this._property = _this._getProperty(_this.propertyPath);
  51884. return _this;
  51885. }
  51886. Object.defineProperty(ValueCondition, "IsEqual", {
  51887. /**
  51888. * returns the number for IsEqual
  51889. */
  51890. get: function () {
  51891. return ValueCondition._IsEqual;
  51892. },
  51893. enumerable: true,
  51894. configurable: true
  51895. });
  51896. Object.defineProperty(ValueCondition, "IsDifferent", {
  51897. /**
  51898. * Returns the number for IsDifferent
  51899. */
  51900. get: function () {
  51901. return ValueCondition._IsDifferent;
  51902. },
  51903. enumerable: true,
  51904. configurable: true
  51905. });
  51906. Object.defineProperty(ValueCondition, "IsGreater", {
  51907. /**
  51908. * Returns the number for IsGreater
  51909. */
  51910. get: function () {
  51911. return ValueCondition._IsGreater;
  51912. },
  51913. enumerable: true,
  51914. configurable: true
  51915. });
  51916. Object.defineProperty(ValueCondition, "IsLesser", {
  51917. /**
  51918. * Returns the number for IsLesser
  51919. */
  51920. get: function () {
  51921. return ValueCondition._IsLesser;
  51922. },
  51923. enumerable: true,
  51924. configurable: true
  51925. });
  51926. /**
  51927. * Compares the given value with the property value for the specified conditional operator
  51928. * @returns the result of the comparison
  51929. */
  51930. ValueCondition.prototype.isValid = function () {
  51931. switch (this.operator) {
  51932. case ValueCondition.IsGreater:
  51933. return this._effectiveTarget[this._property] > this.value;
  51934. case ValueCondition.IsLesser:
  51935. return this._effectiveTarget[this._property] < this.value;
  51936. case ValueCondition.IsEqual:
  51937. case ValueCondition.IsDifferent:
  51938. var check;
  51939. if (this.value.equals) {
  51940. check = this.value.equals(this._effectiveTarget[this._property]);
  51941. }
  51942. else {
  51943. check = this.value === this._effectiveTarget[this._property];
  51944. }
  51945. return this.operator === ValueCondition.IsEqual ? check : !check;
  51946. }
  51947. return false;
  51948. };
  51949. /**
  51950. * Serialize the ValueCondition into a JSON compatible object
  51951. * @returns serialization object
  51952. */
  51953. ValueCondition.prototype.serialize = function () {
  51954. return this._serialize({
  51955. name: "ValueCondition",
  51956. properties: [
  51957. BABYLON.Action._GetTargetProperty(this._target),
  51958. { name: "propertyPath", value: this.propertyPath },
  51959. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51960. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51961. ]
  51962. });
  51963. };
  51964. /**
  51965. * Gets the name of the conditional operator for the ValueCondition
  51966. * @param operator the conditional operator
  51967. * @returns the name
  51968. */
  51969. ValueCondition.GetOperatorName = function (operator) {
  51970. switch (operator) {
  51971. case ValueCondition._IsEqual: return "IsEqual";
  51972. case ValueCondition._IsDifferent: return "IsDifferent";
  51973. case ValueCondition._IsGreater: return "IsGreater";
  51974. case ValueCondition._IsLesser: return "IsLesser";
  51975. default: return "";
  51976. }
  51977. };
  51978. /**
  51979. * Internal only
  51980. * @hidden
  51981. */
  51982. ValueCondition._IsEqual = 0;
  51983. /**
  51984. * Internal only
  51985. * @hidden
  51986. */
  51987. ValueCondition._IsDifferent = 1;
  51988. /**
  51989. * Internal only
  51990. * @hidden
  51991. */
  51992. ValueCondition._IsGreater = 2;
  51993. /**
  51994. * Internal only
  51995. * @hidden
  51996. */
  51997. ValueCondition._IsLesser = 3;
  51998. return ValueCondition;
  51999. }(Condition));
  52000. BABYLON.ValueCondition = ValueCondition;
  52001. /**
  52002. * Defines a predicate condition as an extension of Condition
  52003. */
  52004. var PredicateCondition = /** @class */ (function (_super) {
  52005. __extends(PredicateCondition, _super);
  52006. /**
  52007. * Creates a new PredicateCondition
  52008. * @param actionManager manager for the action the condition applies to
  52009. * @param predicate defines the predicate function used to validate the condition
  52010. */
  52011. function PredicateCondition(actionManager,
  52012. /** defines the predicate function used to validate the condition */
  52013. predicate) {
  52014. var _this = _super.call(this, actionManager) || this;
  52015. _this.predicate = predicate;
  52016. return _this;
  52017. }
  52018. /**
  52019. * @returns the validity of the predicate condition
  52020. */
  52021. PredicateCondition.prototype.isValid = function () {
  52022. return this.predicate();
  52023. };
  52024. return PredicateCondition;
  52025. }(Condition));
  52026. BABYLON.PredicateCondition = PredicateCondition;
  52027. /**
  52028. * Defines a state condition as an extension of Condition
  52029. */
  52030. var StateCondition = /** @class */ (function (_super) {
  52031. __extends(StateCondition, _super);
  52032. /**
  52033. * Creates a new StateCondition
  52034. * @param actionManager manager for the action the condition applies to
  52035. * @param target of the condition
  52036. * @param value to compare with target state
  52037. */
  52038. function StateCondition(actionManager, target, value) {
  52039. var _this = _super.call(this, actionManager) || this;
  52040. _this.value = value;
  52041. _this._target = target;
  52042. return _this;
  52043. }
  52044. /**
  52045. * @returns the validity of the state
  52046. */
  52047. StateCondition.prototype.isValid = function () {
  52048. return this._target.state === this.value;
  52049. };
  52050. /**
  52051. * Serialize the StateCondition into a JSON compatible object
  52052. * @returns serialization object
  52053. */
  52054. StateCondition.prototype.serialize = function () {
  52055. return this._serialize({
  52056. name: "StateCondition",
  52057. properties: [
  52058. BABYLON.Action._GetTargetProperty(this._target),
  52059. { name: "value", value: this.value }
  52060. ]
  52061. });
  52062. };
  52063. return StateCondition;
  52064. }(Condition));
  52065. BABYLON.StateCondition = StateCondition;
  52066. })(BABYLON || (BABYLON = {}));
  52067. //# sourceMappingURL=babylon.condition.js.map
  52068. var BABYLON;
  52069. (function (BABYLON) {
  52070. /**
  52071. * The action to be carried out following a trigger
  52072. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52073. */
  52074. var Action = /** @class */ (function () {
  52075. /**
  52076. * Creates a new Action
  52077. * @param triggerOptions the trigger, with or without parameters, for the action
  52078. * @param condition an optional determinant of action
  52079. */
  52080. function Action(
  52081. /** the trigger, with or without parameters, for the action */
  52082. triggerOptions, condition) {
  52083. this.triggerOptions = triggerOptions;
  52084. /**
  52085. * An event triggered prior to action being executed.
  52086. */
  52087. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52088. if (triggerOptions.parameter) {
  52089. this.trigger = triggerOptions.trigger;
  52090. this._triggerParameter = triggerOptions.parameter;
  52091. }
  52092. else {
  52093. this.trigger = triggerOptions;
  52094. }
  52095. this._nextActiveAction = this;
  52096. this._condition = condition;
  52097. }
  52098. /**
  52099. * Internal only
  52100. * @hidden
  52101. */
  52102. Action.prototype._prepare = function () {
  52103. };
  52104. /**
  52105. * Gets the trigger parameters
  52106. * @returns the trigger parameters
  52107. */
  52108. Action.prototype.getTriggerParameter = function () {
  52109. return this._triggerParameter;
  52110. };
  52111. /**
  52112. * Internal only - executes current action event
  52113. * @hidden
  52114. */
  52115. Action.prototype._executeCurrent = function (evt) {
  52116. if (this._nextActiveAction._condition) {
  52117. var condition = this._nextActiveAction._condition;
  52118. var currentRenderId = this._actionManager.getScene().getRenderId();
  52119. // We cache the current evaluation for the current frame
  52120. if (condition._evaluationId === currentRenderId) {
  52121. if (!condition._currentResult) {
  52122. return;
  52123. }
  52124. }
  52125. else {
  52126. condition._evaluationId = currentRenderId;
  52127. if (!condition.isValid()) {
  52128. condition._currentResult = false;
  52129. return;
  52130. }
  52131. condition._currentResult = true;
  52132. }
  52133. }
  52134. this.onBeforeExecuteObservable.notifyObservers(this);
  52135. this._nextActiveAction.execute(evt);
  52136. this.skipToNextActiveAction();
  52137. };
  52138. /**
  52139. * Execute placeholder for child classes
  52140. * @param evt optional action event
  52141. */
  52142. Action.prototype.execute = function (evt) {
  52143. };
  52144. /**
  52145. * Skips to next active action
  52146. */
  52147. Action.prototype.skipToNextActiveAction = function () {
  52148. if (this._nextActiveAction._child) {
  52149. if (!this._nextActiveAction._child._actionManager) {
  52150. this._nextActiveAction._child._actionManager = this._actionManager;
  52151. }
  52152. this._nextActiveAction = this._nextActiveAction._child;
  52153. }
  52154. else {
  52155. this._nextActiveAction = this;
  52156. }
  52157. };
  52158. /**
  52159. * Adds action to chain of actions, may be a DoNothingAction
  52160. * @param action defines the next action to execute
  52161. * @returns The action passed in
  52162. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52163. */
  52164. Action.prototype.then = function (action) {
  52165. this._child = action;
  52166. action._actionManager = this._actionManager;
  52167. action._prepare();
  52168. return action;
  52169. };
  52170. /**
  52171. * Internal only
  52172. * @hidden
  52173. */
  52174. Action.prototype._getProperty = function (propertyPath) {
  52175. return this._actionManager._getProperty(propertyPath);
  52176. };
  52177. /**
  52178. * Internal only
  52179. * @hidden
  52180. */
  52181. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52182. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52183. };
  52184. /**
  52185. * Serialize placeholder for child classes
  52186. * @param parent of child
  52187. * @returns the serialized object
  52188. */
  52189. Action.prototype.serialize = function (parent) {
  52190. };
  52191. /**
  52192. * Internal only called by serialize
  52193. * @hidden
  52194. */
  52195. Action.prototype._serialize = function (serializedAction, parent) {
  52196. var serializationObject = {
  52197. type: 1,
  52198. children: [],
  52199. name: serializedAction.name,
  52200. properties: serializedAction.properties || []
  52201. };
  52202. // Serialize child
  52203. if (this._child) {
  52204. this._child.serialize(serializationObject);
  52205. }
  52206. // Check if "this" has a condition
  52207. if (this._condition) {
  52208. var serializedCondition = this._condition.serialize();
  52209. serializedCondition.children.push(serializationObject);
  52210. if (parent) {
  52211. parent.children.push(serializedCondition);
  52212. }
  52213. return serializedCondition;
  52214. }
  52215. if (parent) {
  52216. parent.children.push(serializationObject);
  52217. }
  52218. return serializationObject;
  52219. };
  52220. /**
  52221. * Internal only
  52222. * @hidden
  52223. */
  52224. Action._SerializeValueAsString = function (value) {
  52225. if (typeof value === "number") {
  52226. return value.toString();
  52227. }
  52228. if (typeof value === "boolean") {
  52229. return value ? "true" : "false";
  52230. }
  52231. if (value instanceof BABYLON.Vector2) {
  52232. return value.x + ", " + value.y;
  52233. }
  52234. if (value instanceof BABYLON.Vector3) {
  52235. return value.x + ", " + value.y + ", " + value.z;
  52236. }
  52237. if (value instanceof BABYLON.Color3) {
  52238. return value.r + ", " + value.g + ", " + value.b;
  52239. }
  52240. if (value instanceof BABYLON.Color4) {
  52241. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52242. }
  52243. return value; // string
  52244. };
  52245. /**
  52246. * Internal only
  52247. * @hidden
  52248. */
  52249. Action._GetTargetProperty = function (target) {
  52250. return {
  52251. name: "target",
  52252. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52253. : target instanceof BABYLON.Light ? "LightProperties"
  52254. : target instanceof BABYLON.Camera ? "CameraProperties"
  52255. : "SceneProperties",
  52256. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52257. };
  52258. };
  52259. return Action;
  52260. }());
  52261. BABYLON.Action = Action;
  52262. })(BABYLON || (BABYLON = {}));
  52263. //# sourceMappingURL=babylon.action.js.map
  52264. var BABYLON;
  52265. (function (BABYLON) {
  52266. /**
  52267. * ActionEvent is the event being sent when an action is triggered.
  52268. */
  52269. var ActionEvent = /** @class */ (function () {
  52270. /**
  52271. * Creates a new ActionEvent
  52272. * @param source The mesh or sprite that triggered the action
  52273. * @param pointerX The X mouse cursor position at the time of the event
  52274. * @param pointerY The Y mouse cursor position at the time of the event
  52275. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52276. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52277. * @param additionalData additional data for the event
  52278. */
  52279. function ActionEvent(
  52280. /** The mesh or sprite that triggered the action */
  52281. source,
  52282. /** The X mouse cursor position at the time of the event */
  52283. pointerX,
  52284. /** The Y mouse cursor position at the time of the event */
  52285. pointerY,
  52286. /** The mesh that is currently pointed at (can be null) */
  52287. meshUnderPointer,
  52288. /** the original (browser) event that triggered the ActionEvent */
  52289. sourceEvent,
  52290. /** additional data for the event */
  52291. additionalData) {
  52292. this.source = source;
  52293. this.pointerX = pointerX;
  52294. this.pointerY = pointerY;
  52295. this.meshUnderPointer = meshUnderPointer;
  52296. this.sourceEvent = sourceEvent;
  52297. this.additionalData = additionalData;
  52298. }
  52299. /**
  52300. * Helper function to auto-create an ActionEvent from a source mesh.
  52301. * @param source The source mesh that triggered the event
  52302. * @param evt The original (browser) event
  52303. * @param additionalData additional data for the event
  52304. * @returns the new ActionEvent
  52305. */
  52306. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52307. var scene = source.getScene();
  52308. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52309. };
  52310. /**
  52311. * Helper function to auto-create an ActionEvent from a source sprite
  52312. * @param source The source sprite that triggered the event
  52313. * @param scene Scene associated with the sprite
  52314. * @param evt The original (browser) event
  52315. * @param additionalData additional data for the event
  52316. * @returns the new ActionEvent
  52317. */
  52318. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52319. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52320. };
  52321. /**
  52322. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52323. * @param scene the scene where the event occurred
  52324. * @param evt The original (browser) event
  52325. * @returns the new ActionEvent
  52326. */
  52327. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52328. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52329. };
  52330. /**
  52331. * Helper function to auto-create an ActionEvent from a primitive
  52332. * @param prim defines the target primitive
  52333. * @param pointerPos defines the pointer position
  52334. * @param evt The original (browser) event
  52335. * @param additionalData additional data for the event
  52336. * @returns the new ActionEvent
  52337. */
  52338. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52339. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52340. };
  52341. return ActionEvent;
  52342. }());
  52343. BABYLON.ActionEvent = ActionEvent;
  52344. /**
  52345. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52346. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52347. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52348. */
  52349. var ActionManager = /** @class */ (function () {
  52350. /**
  52351. * Creates a new action manager
  52352. * @param scene defines the hosting scene
  52353. */
  52354. function ActionManager(scene) {
  52355. // Members
  52356. /** Gets the list of actions */
  52357. this.actions = new Array();
  52358. /** Gets the cursor to use when hovering items */
  52359. this.hoverCursor = '';
  52360. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52361. scene.actionManagers.push(this);
  52362. }
  52363. Object.defineProperty(ActionManager, "NothingTrigger", {
  52364. /**
  52365. * Nothing
  52366. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52367. */
  52368. get: function () {
  52369. return ActionManager._NothingTrigger;
  52370. },
  52371. enumerable: true,
  52372. configurable: true
  52373. });
  52374. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52375. /**
  52376. * On pick
  52377. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52378. */
  52379. get: function () {
  52380. return ActionManager._OnPickTrigger;
  52381. },
  52382. enumerable: true,
  52383. configurable: true
  52384. });
  52385. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52386. /**
  52387. * On left pick
  52388. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52389. */
  52390. get: function () {
  52391. return ActionManager._OnLeftPickTrigger;
  52392. },
  52393. enumerable: true,
  52394. configurable: true
  52395. });
  52396. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52397. /**
  52398. * On right pick
  52399. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52400. */
  52401. get: function () {
  52402. return ActionManager._OnRightPickTrigger;
  52403. },
  52404. enumerable: true,
  52405. configurable: true
  52406. });
  52407. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52408. /**
  52409. * On center pick
  52410. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52411. */
  52412. get: function () {
  52413. return ActionManager._OnCenterPickTrigger;
  52414. },
  52415. enumerable: true,
  52416. configurable: true
  52417. });
  52418. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52419. /**
  52420. * On pick down
  52421. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52422. */
  52423. get: function () {
  52424. return ActionManager._OnPickDownTrigger;
  52425. },
  52426. enumerable: true,
  52427. configurable: true
  52428. });
  52429. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52430. /**
  52431. * On double pick
  52432. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52433. */
  52434. get: function () {
  52435. return ActionManager._OnDoublePickTrigger;
  52436. },
  52437. enumerable: true,
  52438. configurable: true
  52439. });
  52440. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52441. /**
  52442. * On pick up
  52443. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52444. */
  52445. get: function () {
  52446. return ActionManager._OnPickUpTrigger;
  52447. },
  52448. enumerable: true,
  52449. configurable: true
  52450. });
  52451. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52452. /**
  52453. * On pick out.
  52454. * This trigger will only be raised if you also declared a OnPickDown
  52455. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52456. */
  52457. get: function () {
  52458. return ActionManager._OnPickOutTrigger;
  52459. },
  52460. enumerable: true,
  52461. configurable: true
  52462. });
  52463. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52464. /**
  52465. * On long press
  52466. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52467. */
  52468. get: function () {
  52469. return ActionManager._OnLongPressTrigger;
  52470. },
  52471. enumerable: true,
  52472. configurable: true
  52473. });
  52474. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52475. /**
  52476. * On pointer over
  52477. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52478. */
  52479. get: function () {
  52480. return ActionManager._OnPointerOverTrigger;
  52481. },
  52482. enumerable: true,
  52483. configurable: true
  52484. });
  52485. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52486. /**
  52487. * On pointer out
  52488. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52489. */
  52490. get: function () {
  52491. return ActionManager._OnPointerOutTrigger;
  52492. },
  52493. enumerable: true,
  52494. configurable: true
  52495. });
  52496. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52497. /**
  52498. * On every frame
  52499. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52500. */
  52501. get: function () {
  52502. return ActionManager._OnEveryFrameTrigger;
  52503. },
  52504. enumerable: true,
  52505. configurable: true
  52506. });
  52507. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52508. /**
  52509. * On intersection enter
  52510. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52511. */
  52512. get: function () {
  52513. return ActionManager._OnIntersectionEnterTrigger;
  52514. },
  52515. enumerable: true,
  52516. configurable: true
  52517. });
  52518. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52519. /**
  52520. * On intersection exit
  52521. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52522. */
  52523. get: function () {
  52524. return ActionManager._OnIntersectionExitTrigger;
  52525. },
  52526. enumerable: true,
  52527. configurable: true
  52528. });
  52529. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52530. /**
  52531. * On key down
  52532. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52533. */
  52534. get: function () {
  52535. return ActionManager._OnKeyDownTrigger;
  52536. },
  52537. enumerable: true,
  52538. configurable: true
  52539. });
  52540. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52541. /**
  52542. * On key up
  52543. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52544. */
  52545. get: function () {
  52546. return ActionManager._OnKeyUpTrigger;
  52547. },
  52548. enumerable: true,
  52549. configurable: true
  52550. });
  52551. // Methods
  52552. /**
  52553. * Releases all associated resources
  52554. */
  52555. ActionManager.prototype.dispose = function () {
  52556. var index = this._scene.actionManagers.indexOf(this);
  52557. for (var i = 0; i < this.actions.length; i++) {
  52558. var action = this.actions[i];
  52559. ActionManager.Triggers[action.trigger]--;
  52560. if (ActionManager.Triggers[action.trigger] === 0) {
  52561. delete ActionManager.Triggers[action.trigger];
  52562. }
  52563. }
  52564. if (index > -1) {
  52565. this._scene.actionManagers.splice(index, 1);
  52566. }
  52567. };
  52568. /**
  52569. * Gets hosting scene
  52570. * @returns the hosting scene
  52571. */
  52572. ActionManager.prototype.getScene = function () {
  52573. return this._scene;
  52574. };
  52575. /**
  52576. * Does this action manager handles actions of any of the given triggers
  52577. * @param triggers defines the triggers to be tested
  52578. * @return a boolean indicating whether one (or more) of the triggers is handled
  52579. */
  52580. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52581. for (var index = 0; index < this.actions.length; index++) {
  52582. var action = this.actions[index];
  52583. if (triggers.indexOf(action.trigger) > -1) {
  52584. return true;
  52585. }
  52586. }
  52587. return false;
  52588. };
  52589. /**
  52590. * Does this action manager handles actions of a given trigger
  52591. * @param trigger defines the trigger to be tested
  52592. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52593. * @return whether the trigger is handled
  52594. */
  52595. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52596. for (var index = 0; index < this.actions.length; index++) {
  52597. var action = this.actions[index];
  52598. if (action.trigger === trigger) {
  52599. if (parameterPredicate) {
  52600. if (parameterPredicate(action.getTriggerParameter())) {
  52601. return true;
  52602. }
  52603. }
  52604. else {
  52605. return true;
  52606. }
  52607. }
  52608. }
  52609. return false;
  52610. };
  52611. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52612. /**
  52613. * Does this action manager has pointer triggers
  52614. */
  52615. get: function () {
  52616. for (var index = 0; index < this.actions.length; index++) {
  52617. var action = this.actions[index];
  52618. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52619. return true;
  52620. }
  52621. }
  52622. return false;
  52623. },
  52624. enumerable: true,
  52625. configurable: true
  52626. });
  52627. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52628. /**
  52629. * Does this action manager has pick triggers
  52630. */
  52631. get: function () {
  52632. for (var index = 0; index < this.actions.length; index++) {
  52633. var action = this.actions[index];
  52634. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52635. return true;
  52636. }
  52637. }
  52638. return false;
  52639. },
  52640. enumerable: true,
  52641. configurable: true
  52642. });
  52643. Object.defineProperty(ActionManager, "HasTriggers", {
  52644. /**
  52645. * Does exist one action manager with at least one trigger
  52646. **/
  52647. get: function () {
  52648. for (var t in ActionManager.Triggers) {
  52649. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52650. return true;
  52651. }
  52652. }
  52653. return false;
  52654. },
  52655. enumerable: true,
  52656. configurable: true
  52657. });
  52658. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52659. /**
  52660. * Does exist one action manager with at least one pick trigger
  52661. **/
  52662. get: function () {
  52663. for (var t in ActionManager.Triggers) {
  52664. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52665. var t_int = parseInt(t);
  52666. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52667. return true;
  52668. }
  52669. }
  52670. }
  52671. return false;
  52672. },
  52673. enumerable: true,
  52674. configurable: true
  52675. });
  52676. /**
  52677. * Does exist one action manager that handles actions of a given trigger
  52678. * @param trigger defines the trigger to be tested
  52679. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52680. **/
  52681. ActionManager.HasSpecificTrigger = function (trigger) {
  52682. for (var t in ActionManager.Triggers) {
  52683. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52684. var t_int = parseInt(t);
  52685. if (t_int === trigger) {
  52686. return true;
  52687. }
  52688. }
  52689. }
  52690. return false;
  52691. };
  52692. /**
  52693. * Registers an action to this action manager
  52694. * @param action defines the action to be registered
  52695. * @return the action amended (prepared) after registration
  52696. */
  52697. ActionManager.prototype.registerAction = function (action) {
  52698. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52699. if (this.getScene().actionManager !== this) {
  52700. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52701. return null;
  52702. }
  52703. }
  52704. this.actions.push(action);
  52705. if (ActionManager.Triggers[action.trigger]) {
  52706. ActionManager.Triggers[action.trigger]++;
  52707. }
  52708. else {
  52709. ActionManager.Triggers[action.trigger] = 1;
  52710. }
  52711. action._actionManager = this;
  52712. action._prepare();
  52713. return action;
  52714. };
  52715. /**
  52716. * Unregisters an action to this action manager
  52717. * @param action defines the action to be unregistered
  52718. * @return a boolean indicating whether the action has been unregistered
  52719. */
  52720. ActionManager.prototype.unregisterAction = function (action) {
  52721. var index = this.actions.indexOf(action);
  52722. if (index !== -1) {
  52723. this.actions.splice(index, 1);
  52724. ActionManager.Triggers[action.trigger] -= 1;
  52725. if (ActionManager.Triggers[action.trigger] === 0) {
  52726. delete ActionManager.Triggers[action.trigger];
  52727. }
  52728. delete action._actionManager;
  52729. return true;
  52730. }
  52731. return false;
  52732. };
  52733. /**
  52734. * Process a specific trigger
  52735. * @param trigger defines the trigger to process
  52736. * @param evt defines the event details to be processed
  52737. */
  52738. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52739. for (var index = 0; index < this.actions.length; index++) {
  52740. var action = this.actions[index];
  52741. if (action.trigger === trigger) {
  52742. if (evt) {
  52743. if (trigger === ActionManager.OnKeyUpTrigger
  52744. || trigger === ActionManager.OnKeyDownTrigger) {
  52745. var parameter = action.getTriggerParameter();
  52746. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52747. if (!parameter.toLowerCase) {
  52748. continue;
  52749. }
  52750. var lowerCase = parameter.toLowerCase();
  52751. if (lowerCase !== evt.sourceEvent.key) {
  52752. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52753. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52754. if (actualkey !== lowerCase) {
  52755. continue;
  52756. }
  52757. }
  52758. }
  52759. }
  52760. }
  52761. action._executeCurrent(evt);
  52762. }
  52763. }
  52764. };
  52765. /** @hidden */
  52766. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52767. var properties = propertyPath.split(".");
  52768. for (var index = 0; index < properties.length - 1; index++) {
  52769. target = target[properties[index]];
  52770. }
  52771. return target;
  52772. };
  52773. /** @hidden */
  52774. ActionManager.prototype._getProperty = function (propertyPath) {
  52775. var properties = propertyPath.split(".");
  52776. return properties[properties.length - 1];
  52777. };
  52778. /**
  52779. * Serialize this manager to a JSON object
  52780. * @param name defines the property name to store this manager
  52781. * @returns a JSON representation of this manager
  52782. */
  52783. ActionManager.prototype.serialize = function (name) {
  52784. var root = {
  52785. children: new Array(),
  52786. name: name,
  52787. type: 3,
  52788. properties: new Array() // Empty for root but required
  52789. };
  52790. for (var i = 0; i < this.actions.length; i++) {
  52791. var triggerObject = {
  52792. type: 0,
  52793. children: new Array(),
  52794. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52795. properties: new Array()
  52796. };
  52797. var triggerOptions = this.actions[i].triggerOptions;
  52798. if (triggerOptions && typeof triggerOptions !== "number") {
  52799. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52800. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52801. }
  52802. else {
  52803. var parameter = {};
  52804. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52805. if (triggerOptions.parameter.mesh) {
  52806. parameter._meshId = triggerOptions.parameter.mesh.id;
  52807. }
  52808. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52809. }
  52810. }
  52811. // Serialize child action, recursively
  52812. this.actions[i].serialize(triggerObject);
  52813. // Add serialized trigger
  52814. root.children.push(triggerObject);
  52815. }
  52816. return root;
  52817. };
  52818. /**
  52819. * Creates a new ActionManager from a JSON data
  52820. * @param parsedActions defines the JSON data to read from
  52821. * @param object defines the hosting mesh
  52822. * @param scene defines the hosting scene
  52823. */
  52824. ActionManager.Parse = function (parsedActions, object, scene) {
  52825. var actionManager = new ActionManager(scene);
  52826. if (object === null)
  52827. scene.actionManager = actionManager;
  52828. else
  52829. object.actionManager = actionManager;
  52830. // instanciate a new object
  52831. var instanciate = function (name, params) {
  52832. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52833. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52834. newInstance.constructor.apply(newInstance, params);
  52835. return newInstance;
  52836. };
  52837. var parseParameter = function (name, value, target, propertyPath) {
  52838. if (propertyPath === null) {
  52839. // String, boolean or float
  52840. var floatValue = parseFloat(value);
  52841. if (value === "true" || value === "false")
  52842. return value === "true";
  52843. else
  52844. return isNaN(floatValue) ? value : floatValue;
  52845. }
  52846. var effectiveTarget = propertyPath.split(".");
  52847. var values = value.split(",");
  52848. // Get effective Target
  52849. for (var i = 0; i < effectiveTarget.length; i++) {
  52850. target = target[effectiveTarget[i]];
  52851. }
  52852. // Return appropriate value with its type
  52853. if (typeof (target) === "boolean")
  52854. return values[0] === "true";
  52855. if (typeof (target) === "string")
  52856. return values[0];
  52857. // Parameters with multiple values such as Vector3 etc.
  52858. var split = new Array();
  52859. for (var i = 0; i < values.length; i++)
  52860. split.push(parseFloat(values[i]));
  52861. if (target instanceof BABYLON.Vector3)
  52862. return BABYLON.Vector3.FromArray(split);
  52863. if (target instanceof BABYLON.Vector4)
  52864. return BABYLON.Vector4.FromArray(split);
  52865. if (target instanceof BABYLON.Color3)
  52866. return BABYLON.Color3.FromArray(split);
  52867. if (target instanceof BABYLON.Color4)
  52868. return BABYLON.Color4.FromArray(split);
  52869. return parseFloat(values[0]);
  52870. };
  52871. // traverse graph per trigger
  52872. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52873. if (combineArray === void 0) { combineArray = null; }
  52874. if (parsedAction.detached)
  52875. return;
  52876. var parameters = new Array();
  52877. var target = null;
  52878. var propertyPath = null;
  52879. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52880. // Parameters
  52881. if (parsedAction.type === 2)
  52882. parameters.push(actionManager);
  52883. else
  52884. parameters.push(trigger);
  52885. if (combine) {
  52886. var actions = new Array();
  52887. for (var j = 0; j < parsedAction.combine.length; j++) {
  52888. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52889. }
  52890. parameters.push(actions);
  52891. }
  52892. else {
  52893. for (var i = 0; i < parsedAction.properties.length; i++) {
  52894. var value = parsedAction.properties[i].value;
  52895. var name = parsedAction.properties[i].name;
  52896. var targetType = parsedAction.properties[i].targetType;
  52897. if (name === "target")
  52898. if (targetType !== null && targetType === "SceneProperties")
  52899. value = target = scene;
  52900. else
  52901. value = target = scene.getNodeByName(value);
  52902. else if (name === "parent")
  52903. value = scene.getNodeByName(value);
  52904. else if (name === "sound")
  52905. value = scene.getSoundByName(value);
  52906. else if (name !== "propertyPath") {
  52907. if (parsedAction.type === 2 && name === "operator")
  52908. value = BABYLON.ValueCondition[value];
  52909. else
  52910. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52911. }
  52912. else {
  52913. propertyPath = value;
  52914. }
  52915. parameters.push(value);
  52916. }
  52917. }
  52918. if (combineArray === null) {
  52919. parameters.push(condition);
  52920. }
  52921. else {
  52922. parameters.push(null);
  52923. }
  52924. // If interpolate value action
  52925. if (parsedAction.name === "InterpolateValueAction") {
  52926. var param = parameters[parameters.length - 2];
  52927. parameters[parameters.length - 1] = param;
  52928. parameters[parameters.length - 2] = condition;
  52929. }
  52930. // Action or condition(s) and not CombineAction
  52931. var newAction = instanciate(parsedAction.name, parameters);
  52932. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52933. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52934. if (action)
  52935. action.then(nothing);
  52936. else
  52937. actionManager.registerAction(nothing);
  52938. action = nothing;
  52939. }
  52940. if (combineArray === null) {
  52941. if (newAction instanceof BABYLON.Condition) {
  52942. condition = newAction;
  52943. newAction = action;
  52944. }
  52945. else {
  52946. condition = null;
  52947. if (action)
  52948. action.then(newAction);
  52949. else
  52950. actionManager.registerAction(newAction);
  52951. }
  52952. }
  52953. else {
  52954. combineArray.push(newAction);
  52955. }
  52956. for (var i = 0; i < parsedAction.children.length; i++)
  52957. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52958. };
  52959. // triggers
  52960. for (var i = 0; i < parsedActions.children.length; i++) {
  52961. var triggerParams;
  52962. var trigger = parsedActions.children[i];
  52963. if (trigger.properties.length > 0) {
  52964. var param = trigger.properties[0].value;
  52965. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52966. if (value._meshId) {
  52967. value.mesh = scene.getMeshByID(value._meshId);
  52968. }
  52969. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52970. }
  52971. else
  52972. triggerParams = ActionManager[trigger.name];
  52973. for (var j = 0; j < trigger.children.length; j++) {
  52974. if (!trigger.detached)
  52975. traverse(trigger.children[j], triggerParams, null, null);
  52976. }
  52977. }
  52978. };
  52979. /**
  52980. * Get a trigger name by index
  52981. * @param trigger defines the trigger index
  52982. * @returns a trigger name
  52983. */
  52984. ActionManager.GetTriggerName = function (trigger) {
  52985. switch (trigger) {
  52986. case 0: return "NothingTrigger";
  52987. case 1: return "OnPickTrigger";
  52988. case 2: return "OnLeftPickTrigger";
  52989. case 3: return "OnRightPickTrigger";
  52990. case 4: return "OnCenterPickTrigger";
  52991. case 5: return "OnPickDownTrigger";
  52992. case 6: return "OnPickUpTrigger";
  52993. case 7: return "OnLongPressTrigger";
  52994. case 8: return "OnPointerOverTrigger";
  52995. case 9: return "OnPointerOutTrigger";
  52996. case 10: return "OnEveryFrameTrigger";
  52997. case 11: return "OnIntersectionEnterTrigger";
  52998. case 12: return "OnIntersectionExitTrigger";
  52999. case 13: return "OnKeyDownTrigger";
  53000. case 14: return "OnKeyUpTrigger";
  53001. case 15: return "OnPickOutTrigger";
  53002. default: return "";
  53003. }
  53004. };
  53005. // Statics
  53006. ActionManager._NothingTrigger = 0;
  53007. ActionManager._OnPickTrigger = 1;
  53008. ActionManager._OnLeftPickTrigger = 2;
  53009. ActionManager._OnRightPickTrigger = 3;
  53010. ActionManager._OnCenterPickTrigger = 4;
  53011. ActionManager._OnPickDownTrigger = 5;
  53012. ActionManager._OnDoublePickTrigger = 6;
  53013. ActionManager._OnPickUpTrigger = 7;
  53014. ActionManager._OnLongPressTrigger = 8;
  53015. ActionManager._OnPointerOverTrigger = 9;
  53016. ActionManager._OnPointerOutTrigger = 10;
  53017. ActionManager._OnEveryFrameTrigger = 11;
  53018. ActionManager._OnIntersectionEnterTrigger = 12;
  53019. ActionManager._OnIntersectionExitTrigger = 13;
  53020. ActionManager._OnKeyDownTrigger = 14;
  53021. ActionManager._OnKeyUpTrigger = 15;
  53022. ActionManager._OnPickOutTrigger = 16;
  53023. /** Gets the list of active triggers */
  53024. ActionManager.Triggers = {};
  53025. return ActionManager;
  53026. }());
  53027. BABYLON.ActionManager = ActionManager;
  53028. })(BABYLON || (BABYLON = {}));
  53029. //# sourceMappingURL=babylon.actionManager.js.map
  53030. var BABYLON;
  53031. (function (BABYLON) {
  53032. var InterpolateValueAction = /** @class */ (function (_super) {
  53033. __extends(InterpolateValueAction, _super);
  53034. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53035. if (duration === void 0) { duration = 1000; }
  53036. var _this = _super.call(this, triggerOptions, condition) || this;
  53037. _this.propertyPath = propertyPath;
  53038. _this.value = value;
  53039. _this.duration = duration;
  53040. _this.stopOtherAnimations = stopOtherAnimations;
  53041. _this.onInterpolationDone = onInterpolationDone;
  53042. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53043. _this._target = _this._effectiveTarget = target;
  53044. return _this;
  53045. }
  53046. InterpolateValueAction.prototype._prepare = function () {
  53047. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53048. this._property = this._getProperty(this.propertyPath);
  53049. };
  53050. InterpolateValueAction.prototype.execute = function () {
  53051. var _this = this;
  53052. var scene = this._actionManager.getScene();
  53053. var keys = [
  53054. {
  53055. frame: 0,
  53056. value: this._effectiveTarget[this._property]
  53057. }, {
  53058. frame: 100,
  53059. value: this.value
  53060. }
  53061. ];
  53062. var dataType;
  53063. if (typeof this.value === "number") {
  53064. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53065. }
  53066. else if (this.value instanceof BABYLON.Color3) {
  53067. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53068. }
  53069. else if (this.value instanceof BABYLON.Vector3) {
  53070. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53071. }
  53072. else if (this.value instanceof BABYLON.Matrix) {
  53073. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53074. }
  53075. else if (this.value instanceof BABYLON.Quaternion) {
  53076. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53077. }
  53078. else {
  53079. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53080. return;
  53081. }
  53082. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53083. animation.setKeys(keys);
  53084. if (this.stopOtherAnimations) {
  53085. scene.stopAnimation(this._effectiveTarget);
  53086. }
  53087. var wrapper = function () {
  53088. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53089. if (_this.onInterpolationDone) {
  53090. _this.onInterpolationDone();
  53091. }
  53092. };
  53093. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53094. };
  53095. InterpolateValueAction.prototype.serialize = function (parent) {
  53096. return _super.prototype._serialize.call(this, {
  53097. name: "InterpolateValueAction",
  53098. properties: [
  53099. BABYLON.Action._GetTargetProperty(this._target),
  53100. { name: "propertyPath", value: this.propertyPath },
  53101. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53102. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53103. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53104. ]
  53105. }, parent);
  53106. };
  53107. return InterpolateValueAction;
  53108. }(BABYLON.Action));
  53109. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53110. })(BABYLON || (BABYLON = {}));
  53111. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53112. var BABYLON;
  53113. (function (BABYLON) {
  53114. var SwitchBooleanAction = /** @class */ (function (_super) {
  53115. __extends(SwitchBooleanAction, _super);
  53116. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53117. var _this = _super.call(this, triggerOptions, condition) || this;
  53118. _this.propertyPath = propertyPath;
  53119. _this._target = _this._effectiveTarget = target;
  53120. return _this;
  53121. }
  53122. SwitchBooleanAction.prototype._prepare = function () {
  53123. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53124. this._property = this._getProperty(this.propertyPath);
  53125. };
  53126. SwitchBooleanAction.prototype.execute = function () {
  53127. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53128. };
  53129. SwitchBooleanAction.prototype.serialize = function (parent) {
  53130. return _super.prototype._serialize.call(this, {
  53131. name: "SwitchBooleanAction",
  53132. properties: [
  53133. BABYLON.Action._GetTargetProperty(this._target),
  53134. { name: "propertyPath", value: this.propertyPath }
  53135. ]
  53136. }, parent);
  53137. };
  53138. return SwitchBooleanAction;
  53139. }(BABYLON.Action));
  53140. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53141. var SetStateAction = /** @class */ (function (_super) {
  53142. __extends(SetStateAction, _super);
  53143. function SetStateAction(triggerOptions, target, value, condition) {
  53144. var _this = _super.call(this, triggerOptions, condition) || this;
  53145. _this.value = value;
  53146. _this._target = target;
  53147. return _this;
  53148. }
  53149. SetStateAction.prototype.execute = function () {
  53150. this._target.state = this.value;
  53151. };
  53152. SetStateAction.prototype.serialize = function (parent) {
  53153. return _super.prototype._serialize.call(this, {
  53154. name: "SetStateAction",
  53155. properties: [
  53156. BABYLON.Action._GetTargetProperty(this._target),
  53157. { name: "value", value: this.value }
  53158. ]
  53159. }, parent);
  53160. };
  53161. return SetStateAction;
  53162. }(BABYLON.Action));
  53163. BABYLON.SetStateAction = SetStateAction;
  53164. var SetValueAction = /** @class */ (function (_super) {
  53165. __extends(SetValueAction, _super);
  53166. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53167. var _this = _super.call(this, triggerOptions, condition) || this;
  53168. _this.propertyPath = propertyPath;
  53169. _this.value = value;
  53170. _this._target = _this._effectiveTarget = target;
  53171. return _this;
  53172. }
  53173. SetValueAction.prototype._prepare = function () {
  53174. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53175. this._property = this._getProperty(this.propertyPath);
  53176. };
  53177. SetValueAction.prototype.execute = function () {
  53178. this._effectiveTarget[this._property] = this.value;
  53179. if (this._target.markAsDirty) {
  53180. this._target.markAsDirty(this._property);
  53181. }
  53182. };
  53183. SetValueAction.prototype.serialize = function (parent) {
  53184. return _super.prototype._serialize.call(this, {
  53185. name: "SetValueAction",
  53186. properties: [
  53187. BABYLON.Action._GetTargetProperty(this._target),
  53188. { name: "propertyPath", value: this.propertyPath },
  53189. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53190. ]
  53191. }, parent);
  53192. };
  53193. return SetValueAction;
  53194. }(BABYLON.Action));
  53195. BABYLON.SetValueAction = SetValueAction;
  53196. var IncrementValueAction = /** @class */ (function (_super) {
  53197. __extends(IncrementValueAction, _super);
  53198. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53199. var _this = _super.call(this, triggerOptions, condition) || this;
  53200. _this.propertyPath = propertyPath;
  53201. _this.value = value;
  53202. _this._target = _this._effectiveTarget = target;
  53203. return _this;
  53204. }
  53205. IncrementValueAction.prototype._prepare = function () {
  53206. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53207. this._property = this._getProperty(this.propertyPath);
  53208. if (typeof this._effectiveTarget[this._property] !== "number") {
  53209. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53210. }
  53211. };
  53212. IncrementValueAction.prototype.execute = function () {
  53213. this._effectiveTarget[this._property] += this.value;
  53214. if (this._target.markAsDirty) {
  53215. this._target.markAsDirty(this._property);
  53216. }
  53217. };
  53218. IncrementValueAction.prototype.serialize = function (parent) {
  53219. return _super.prototype._serialize.call(this, {
  53220. name: "IncrementValueAction",
  53221. properties: [
  53222. BABYLON.Action._GetTargetProperty(this._target),
  53223. { name: "propertyPath", value: this.propertyPath },
  53224. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53225. ]
  53226. }, parent);
  53227. };
  53228. return IncrementValueAction;
  53229. }(BABYLON.Action));
  53230. BABYLON.IncrementValueAction = IncrementValueAction;
  53231. var PlayAnimationAction = /** @class */ (function (_super) {
  53232. __extends(PlayAnimationAction, _super);
  53233. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53234. var _this = _super.call(this, triggerOptions, condition) || this;
  53235. _this.from = from;
  53236. _this.to = to;
  53237. _this.loop = loop;
  53238. _this._target = target;
  53239. return _this;
  53240. }
  53241. PlayAnimationAction.prototype._prepare = function () {
  53242. };
  53243. PlayAnimationAction.prototype.execute = function () {
  53244. var scene = this._actionManager.getScene();
  53245. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53246. };
  53247. PlayAnimationAction.prototype.serialize = function (parent) {
  53248. return _super.prototype._serialize.call(this, {
  53249. name: "PlayAnimationAction",
  53250. properties: [
  53251. BABYLON.Action._GetTargetProperty(this._target),
  53252. { name: "from", value: String(this.from) },
  53253. { name: "to", value: String(this.to) },
  53254. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53255. ]
  53256. }, parent);
  53257. };
  53258. return PlayAnimationAction;
  53259. }(BABYLON.Action));
  53260. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53261. var StopAnimationAction = /** @class */ (function (_super) {
  53262. __extends(StopAnimationAction, _super);
  53263. function StopAnimationAction(triggerOptions, target, condition) {
  53264. var _this = _super.call(this, triggerOptions, condition) || this;
  53265. _this._target = target;
  53266. return _this;
  53267. }
  53268. StopAnimationAction.prototype._prepare = function () {
  53269. };
  53270. StopAnimationAction.prototype.execute = function () {
  53271. var scene = this._actionManager.getScene();
  53272. scene.stopAnimation(this._target);
  53273. };
  53274. StopAnimationAction.prototype.serialize = function (parent) {
  53275. return _super.prototype._serialize.call(this, {
  53276. name: "StopAnimationAction",
  53277. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53278. }, parent);
  53279. };
  53280. return StopAnimationAction;
  53281. }(BABYLON.Action));
  53282. BABYLON.StopAnimationAction = StopAnimationAction;
  53283. var DoNothingAction = /** @class */ (function (_super) {
  53284. __extends(DoNothingAction, _super);
  53285. function DoNothingAction(triggerOptions, condition) {
  53286. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53287. return _super.call(this, triggerOptions, condition) || this;
  53288. }
  53289. DoNothingAction.prototype.execute = function () {
  53290. };
  53291. DoNothingAction.prototype.serialize = function (parent) {
  53292. return _super.prototype._serialize.call(this, {
  53293. name: "DoNothingAction",
  53294. properties: []
  53295. }, parent);
  53296. };
  53297. return DoNothingAction;
  53298. }(BABYLON.Action));
  53299. BABYLON.DoNothingAction = DoNothingAction;
  53300. var CombineAction = /** @class */ (function (_super) {
  53301. __extends(CombineAction, _super);
  53302. function CombineAction(triggerOptions, children, condition) {
  53303. var _this = _super.call(this, triggerOptions, condition) || this;
  53304. _this.children = children;
  53305. return _this;
  53306. }
  53307. CombineAction.prototype._prepare = function () {
  53308. for (var index = 0; index < this.children.length; index++) {
  53309. this.children[index]._actionManager = this._actionManager;
  53310. this.children[index]._prepare();
  53311. }
  53312. };
  53313. CombineAction.prototype.execute = function (evt) {
  53314. for (var index = 0; index < this.children.length; index++) {
  53315. this.children[index].execute(evt);
  53316. }
  53317. };
  53318. CombineAction.prototype.serialize = function (parent) {
  53319. var serializationObject = _super.prototype._serialize.call(this, {
  53320. name: "CombineAction",
  53321. properties: [],
  53322. combine: []
  53323. }, parent);
  53324. for (var i = 0; i < this.children.length; i++) {
  53325. serializationObject.combine.push(this.children[i].serialize(null));
  53326. }
  53327. return serializationObject;
  53328. };
  53329. return CombineAction;
  53330. }(BABYLON.Action));
  53331. BABYLON.CombineAction = CombineAction;
  53332. var ExecuteCodeAction = /** @class */ (function (_super) {
  53333. __extends(ExecuteCodeAction, _super);
  53334. function ExecuteCodeAction(triggerOptions, func, condition) {
  53335. var _this = _super.call(this, triggerOptions, condition) || this;
  53336. _this.func = func;
  53337. return _this;
  53338. }
  53339. ExecuteCodeAction.prototype.execute = function (evt) {
  53340. this.func(evt);
  53341. };
  53342. return ExecuteCodeAction;
  53343. }(BABYLON.Action));
  53344. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53345. var SetParentAction = /** @class */ (function (_super) {
  53346. __extends(SetParentAction, _super);
  53347. function SetParentAction(triggerOptions, target, parent, condition) {
  53348. var _this = _super.call(this, triggerOptions, condition) || this;
  53349. _this._target = target;
  53350. _this._parent = parent;
  53351. return _this;
  53352. }
  53353. SetParentAction.prototype._prepare = function () {
  53354. };
  53355. SetParentAction.prototype.execute = function () {
  53356. if (this._target.parent === this._parent) {
  53357. return;
  53358. }
  53359. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53360. invertParentWorldMatrix.invert();
  53361. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53362. this._target.parent = this._parent;
  53363. };
  53364. SetParentAction.prototype.serialize = function (parent) {
  53365. return _super.prototype._serialize.call(this, {
  53366. name: "SetParentAction",
  53367. properties: [
  53368. BABYLON.Action._GetTargetProperty(this._target),
  53369. BABYLON.Action._GetTargetProperty(this._parent),
  53370. ]
  53371. }, parent);
  53372. };
  53373. return SetParentAction;
  53374. }(BABYLON.Action));
  53375. BABYLON.SetParentAction = SetParentAction;
  53376. var PlaySoundAction = /** @class */ (function (_super) {
  53377. __extends(PlaySoundAction, _super);
  53378. function PlaySoundAction(triggerOptions, sound, condition) {
  53379. var _this = _super.call(this, triggerOptions, condition) || this;
  53380. _this._sound = sound;
  53381. return _this;
  53382. }
  53383. PlaySoundAction.prototype._prepare = function () {
  53384. };
  53385. PlaySoundAction.prototype.execute = function () {
  53386. if (this._sound !== undefined)
  53387. this._sound.play();
  53388. };
  53389. PlaySoundAction.prototype.serialize = function (parent) {
  53390. return _super.prototype._serialize.call(this, {
  53391. name: "PlaySoundAction",
  53392. properties: [{ name: "sound", value: this._sound.name }]
  53393. }, parent);
  53394. };
  53395. return PlaySoundAction;
  53396. }(BABYLON.Action));
  53397. BABYLON.PlaySoundAction = PlaySoundAction;
  53398. var StopSoundAction = /** @class */ (function (_super) {
  53399. __extends(StopSoundAction, _super);
  53400. function StopSoundAction(triggerOptions, sound, condition) {
  53401. var _this = _super.call(this, triggerOptions, condition) || this;
  53402. _this._sound = sound;
  53403. return _this;
  53404. }
  53405. StopSoundAction.prototype._prepare = function () {
  53406. };
  53407. StopSoundAction.prototype.execute = function () {
  53408. if (this._sound !== undefined)
  53409. this._sound.stop();
  53410. };
  53411. StopSoundAction.prototype.serialize = function (parent) {
  53412. return _super.prototype._serialize.call(this, {
  53413. name: "StopSoundAction",
  53414. properties: [{ name: "sound", value: this._sound.name }]
  53415. }, parent);
  53416. };
  53417. return StopSoundAction;
  53418. }(BABYLON.Action));
  53419. BABYLON.StopSoundAction = StopSoundAction;
  53420. })(BABYLON || (BABYLON = {}));
  53421. //# sourceMappingURL=babylon.directActions.js.map
  53422. var BABYLON;
  53423. (function (BABYLON) {
  53424. var SpriteManager = /** @class */ (function () {
  53425. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53426. if (epsilon === void 0) { epsilon = 0.01; }
  53427. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53428. this.name = name;
  53429. this.sprites = new Array();
  53430. this.renderingGroupId = 0;
  53431. this.layerMask = 0x0FFFFFFF;
  53432. this.fogEnabled = true;
  53433. this.isPickable = false;
  53434. /**
  53435. * An event triggered when the manager is disposed.
  53436. */
  53437. this.onDisposeObservable = new BABYLON.Observable();
  53438. this._vertexBuffers = {};
  53439. this._capacity = capacity;
  53440. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53441. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53442. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53443. if (cellSize.width && cellSize.height) {
  53444. this.cellWidth = cellSize.width;
  53445. this.cellHeight = cellSize.height;
  53446. }
  53447. else if (cellSize !== undefined) {
  53448. this.cellWidth = cellSize;
  53449. this.cellHeight = cellSize;
  53450. }
  53451. else {
  53452. return;
  53453. }
  53454. this._epsilon = epsilon;
  53455. this._scene = scene;
  53456. this._scene.spriteManagers.push(this);
  53457. var indices = [];
  53458. var index = 0;
  53459. for (var count = 0; count < capacity; count++) {
  53460. indices.push(index);
  53461. indices.push(index + 1);
  53462. indices.push(index + 2);
  53463. indices.push(index);
  53464. indices.push(index + 2);
  53465. indices.push(index + 3);
  53466. index += 4;
  53467. }
  53468. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53469. // VBO
  53470. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53471. this._vertexData = new Float32Array(capacity * 16 * 4);
  53472. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53473. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53474. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53475. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53476. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53477. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53478. this._vertexBuffers["options"] = options;
  53479. this._vertexBuffers["cellInfo"] = cellInfo;
  53480. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53481. // Effects
  53482. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53483. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53484. }
  53485. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53486. set: function (callback) {
  53487. if (this._onDisposeObserver) {
  53488. this.onDisposeObservable.remove(this._onDisposeObserver);
  53489. }
  53490. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53491. },
  53492. enumerable: true,
  53493. configurable: true
  53494. });
  53495. Object.defineProperty(SpriteManager.prototype, "texture", {
  53496. get: function () {
  53497. return this._spriteTexture;
  53498. },
  53499. set: function (value) {
  53500. this._spriteTexture = value;
  53501. },
  53502. enumerable: true,
  53503. configurable: true
  53504. });
  53505. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53506. var arrayOffset = index * 16;
  53507. if (offsetX === 0)
  53508. offsetX = this._epsilon;
  53509. else if (offsetX === 1)
  53510. offsetX = 1 - this._epsilon;
  53511. if (offsetY === 0)
  53512. offsetY = this._epsilon;
  53513. else if (offsetY === 1)
  53514. offsetY = 1 - this._epsilon;
  53515. this._vertexData[arrayOffset] = sprite.position.x;
  53516. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53517. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53518. this._vertexData[arrayOffset + 3] = sprite.angle;
  53519. this._vertexData[arrayOffset + 4] = sprite.width;
  53520. this._vertexData[arrayOffset + 5] = sprite.height;
  53521. this._vertexData[arrayOffset + 6] = offsetX;
  53522. this._vertexData[arrayOffset + 7] = offsetY;
  53523. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53524. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53525. var offset = (sprite.cellIndex / rowSize) >> 0;
  53526. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53527. this._vertexData[arrayOffset + 11] = offset;
  53528. // Color
  53529. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53530. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53531. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53532. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53533. };
  53534. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53535. var count = Math.min(this._capacity, this.sprites.length);
  53536. var min = BABYLON.Vector3.Zero();
  53537. var max = BABYLON.Vector3.Zero();
  53538. var distance = Number.MAX_VALUE;
  53539. var currentSprite = null;
  53540. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53541. var cameraView = camera.getViewMatrix();
  53542. for (var index = 0; index < count; index++) {
  53543. var sprite = this.sprites[index];
  53544. if (!sprite) {
  53545. continue;
  53546. }
  53547. if (predicate) {
  53548. if (!predicate(sprite)) {
  53549. continue;
  53550. }
  53551. }
  53552. else if (!sprite.isPickable) {
  53553. continue;
  53554. }
  53555. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53556. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53557. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53558. if (ray.intersectsBoxMinMax(min, max)) {
  53559. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53560. if (distance > currentDistance) {
  53561. distance = currentDistance;
  53562. currentSprite = sprite;
  53563. if (fastCheck) {
  53564. break;
  53565. }
  53566. }
  53567. }
  53568. }
  53569. if (currentSprite) {
  53570. var result = new BABYLON.PickingInfo();
  53571. result.hit = true;
  53572. result.pickedSprite = currentSprite;
  53573. result.distance = distance;
  53574. return result;
  53575. }
  53576. return null;
  53577. };
  53578. SpriteManager.prototype.render = function () {
  53579. // Check
  53580. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53581. return;
  53582. var engine = this._scene.getEngine();
  53583. var baseSize = this._spriteTexture.getBaseSize();
  53584. // Sprites
  53585. var deltaTime = engine.getDeltaTime();
  53586. var max = Math.min(this._capacity, this.sprites.length);
  53587. var rowSize = baseSize.width / this.cellWidth;
  53588. var offset = 0;
  53589. for (var index = 0; index < max; index++) {
  53590. var sprite = this.sprites[index];
  53591. if (!sprite || !sprite.isVisible) {
  53592. continue;
  53593. }
  53594. sprite._animate(deltaTime);
  53595. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53596. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53597. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53598. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53599. }
  53600. this._buffer.update(this._vertexData);
  53601. // Render
  53602. var effect = this._effectBase;
  53603. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53604. effect = this._effectFog;
  53605. }
  53606. engine.enableEffect(effect);
  53607. var viewMatrix = this._scene.getViewMatrix();
  53608. effect.setTexture("diffuseSampler", this._spriteTexture);
  53609. effect.setMatrix("view", viewMatrix);
  53610. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53611. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53612. // Fog
  53613. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53614. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53615. effect.setColor3("vFogColor", this._scene.fogColor);
  53616. }
  53617. // VBOs
  53618. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53619. // Draw order
  53620. engine.setDepthFunctionToLessOrEqual();
  53621. effect.setBool("alphaTest", true);
  53622. engine.setColorWrite(false);
  53623. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53624. engine.setColorWrite(true);
  53625. effect.setBool("alphaTest", false);
  53626. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53627. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53628. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53629. };
  53630. SpriteManager.prototype.dispose = function () {
  53631. if (this._buffer) {
  53632. this._buffer.dispose();
  53633. this._buffer = null;
  53634. }
  53635. if (this._indexBuffer) {
  53636. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53637. this._indexBuffer = null;
  53638. }
  53639. if (this._spriteTexture) {
  53640. this._spriteTexture.dispose();
  53641. this._spriteTexture = null;
  53642. }
  53643. // Remove from scene
  53644. var index = this._scene.spriteManagers.indexOf(this);
  53645. this._scene.spriteManagers.splice(index, 1);
  53646. // Callback
  53647. this.onDisposeObservable.notifyObservers(this);
  53648. this.onDisposeObservable.clear();
  53649. };
  53650. return SpriteManager;
  53651. }());
  53652. BABYLON.SpriteManager = SpriteManager;
  53653. })(BABYLON || (BABYLON = {}));
  53654. //# sourceMappingURL=babylon.spriteManager.js.map
  53655. var BABYLON;
  53656. (function (BABYLON) {
  53657. var Sprite = /** @class */ (function () {
  53658. function Sprite(name, manager) {
  53659. this.name = name;
  53660. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53661. this.width = 1.0;
  53662. this.height = 1.0;
  53663. this.angle = 0;
  53664. this.cellIndex = 0;
  53665. this.invertU = 0;
  53666. this.invertV = 0;
  53667. this.animations = new Array();
  53668. this.isPickable = false;
  53669. this._animationStarted = false;
  53670. this._loopAnimation = false;
  53671. this._fromIndex = 0;
  53672. this._toIndex = 0;
  53673. this._delay = 0;
  53674. this._direction = 1;
  53675. this._time = 0;
  53676. /**
  53677. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53678. */
  53679. this.isVisible = true;
  53680. this._manager = manager;
  53681. this._manager.sprites.push(this);
  53682. this.position = BABYLON.Vector3.Zero();
  53683. }
  53684. Object.defineProperty(Sprite.prototype, "size", {
  53685. get: function () {
  53686. return this.width;
  53687. },
  53688. set: function (value) {
  53689. this.width = value;
  53690. this.height = value;
  53691. },
  53692. enumerable: true,
  53693. configurable: true
  53694. });
  53695. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53696. this._fromIndex = from;
  53697. this._toIndex = to;
  53698. this._loopAnimation = loop;
  53699. this._delay = delay;
  53700. this._animationStarted = true;
  53701. this._direction = from < to ? 1 : -1;
  53702. this.cellIndex = from;
  53703. this._time = 0;
  53704. this._onAnimationEnd = onAnimationEnd;
  53705. };
  53706. Sprite.prototype.stopAnimation = function () {
  53707. this._animationStarted = false;
  53708. };
  53709. Sprite.prototype._animate = function (deltaTime) {
  53710. if (!this._animationStarted)
  53711. return;
  53712. this._time += deltaTime;
  53713. if (this._time > this._delay) {
  53714. this._time = this._time % this._delay;
  53715. this.cellIndex += this._direction;
  53716. if (this.cellIndex > this._toIndex) {
  53717. if (this._loopAnimation) {
  53718. this.cellIndex = this._fromIndex;
  53719. }
  53720. else {
  53721. this.cellIndex = this._toIndex;
  53722. this._animationStarted = false;
  53723. if (this._onAnimationEnd) {
  53724. this._onAnimationEnd();
  53725. }
  53726. if (this.disposeWhenFinishedAnimating) {
  53727. this.dispose();
  53728. }
  53729. }
  53730. }
  53731. }
  53732. };
  53733. Sprite.prototype.dispose = function () {
  53734. for (var i = 0; i < this._manager.sprites.length; i++) {
  53735. if (this._manager.sprites[i] == this) {
  53736. this._manager.sprites.splice(i, 1);
  53737. }
  53738. }
  53739. };
  53740. return Sprite;
  53741. }());
  53742. BABYLON.Sprite = Sprite;
  53743. })(BABYLON || (BABYLON = {}));
  53744. //# sourceMappingURL=babylon.sprite.js.map
  53745. var BABYLON;
  53746. (function (BABYLON) {
  53747. var IntersectionInfo = /** @class */ (function () {
  53748. function IntersectionInfo(bu, bv, distance) {
  53749. this.bu = bu;
  53750. this.bv = bv;
  53751. this.distance = distance;
  53752. this.faceId = 0;
  53753. this.subMeshId = 0;
  53754. }
  53755. return IntersectionInfo;
  53756. }());
  53757. BABYLON.IntersectionInfo = IntersectionInfo;
  53758. /**
  53759. * Information about the result of picking within a scene
  53760. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53761. */
  53762. var PickingInfo = /** @class */ (function () {
  53763. function PickingInfo() {
  53764. /**
  53765. * If the pick collided with an object
  53766. */
  53767. this.hit = false;
  53768. /**
  53769. * Distance away where the pick collided
  53770. */
  53771. this.distance = 0;
  53772. /**
  53773. * The location of pick collision
  53774. */
  53775. this.pickedPoint = null;
  53776. /**
  53777. * The mesh corrisponding the the pick collision
  53778. */
  53779. this.pickedMesh = null;
  53780. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53781. this.bu = 0;
  53782. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53783. this.bv = 0;
  53784. /** The id of the face on the mesh that was picked */
  53785. this.faceId = -1;
  53786. /** Id of the the submesh that was picked */
  53787. this.subMeshId = 0;
  53788. /** If a sprite was picked, this will be the sprite the pick collided with */
  53789. this.pickedSprite = null;
  53790. /**
  53791. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53792. */
  53793. this.originMesh = null;
  53794. /**
  53795. * The ray that was used to perform the picking.
  53796. */
  53797. this.ray = null;
  53798. }
  53799. /**
  53800. * Gets the normal corrispodning to the face the pick collided with
  53801. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53802. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53803. * @returns The normal corrispodning to the face the pick collided with
  53804. */
  53805. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53806. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53807. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53808. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53809. return null;
  53810. }
  53811. var indices = this.pickedMesh.getIndices();
  53812. if (!indices) {
  53813. return null;
  53814. }
  53815. var result;
  53816. if (useVerticesNormals) {
  53817. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53818. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53819. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53820. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53821. normal0 = normal0.scale(this.bu);
  53822. normal1 = normal1.scale(this.bv);
  53823. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53824. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53825. }
  53826. else {
  53827. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53828. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53829. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53830. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53831. var p1p2 = vertex1.subtract(vertex2);
  53832. var p3p2 = vertex3.subtract(vertex2);
  53833. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53834. }
  53835. if (useWorldCoordinates) {
  53836. var wm = this.pickedMesh.getWorldMatrix();
  53837. if (this.pickedMesh.nonUniformScaling) {
  53838. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53839. wm = BABYLON.Tmp.Matrix[0];
  53840. wm.setTranslationFromFloats(0, 0, 0);
  53841. wm.invert();
  53842. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53843. wm = BABYLON.Tmp.Matrix[1];
  53844. }
  53845. result = BABYLON.Vector3.TransformNormal(result, wm);
  53846. }
  53847. result.normalize();
  53848. return result;
  53849. };
  53850. /**
  53851. * Gets the texture coordinates of where the pick occured
  53852. * @returns the vector containing the coordnates of the texture
  53853. */
  53854. PickingInfo.prototype.getTextureCoordinates = function () {
  53855. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53856. return null;
  53857. }
  53858. var indices = this.pickedMesh.getIndices();
  53859. if (!indices) {
  53860. return null;
  53861. }
  53862. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53863. if (!uvs) {
  53864. return null;
  53865. }
  53866. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53867. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53868. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53869. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53870. uv1 = uv1.scale(this.bu);
  53871. uv2 = uv2.scale(this.bv);
  53872. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53873. };
  53874. return PickingInfo;
  53875. }());
  53876. BABYLON.PickingInfo = PickingInfo;
  53877. })(BABYLON || (BABYLON = {}));
  53878. //# sourceMappingURL=babylon.pickingInfo.js.map
  53879. var BABYLON;
  53880. (function (BABYLON) {
  53881. var Ray = /** @class */ (function () {
  53882. function Ray(origin, direction, length) {
  53883. if (length === void 0) { length = Number.MAX_VALUE; }
  53884. this.origin = origin;
  53885. this.direction = direction;
  53886. this.length = length;
  53887. }
  53888. // Methods
  53889. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53890. var d = 0.0;
  53891. var maxValue = Number.MAX_VALUE;
  53892. var inv;
  53893. var min;
  53894. var max;
  53895. var temp;
  53896. if (Math.abs(this.direction.x) < 0.0000001) {
  53897. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53898. return false;
  53899. }
  53900. }
  53901. else {
  53902. inv = 1.0 / this.direction.x;
  53903. min = (minimum.x - this.origin.x) * inv;
  53904. max = (maximum.x - this.origin.x) * inv;
  53905. if (max === -Infinity) {
  53906. max = Infinity;
  53907. }
  53908. if (min > max) {
  53909. temp = min;
  53910. min = max;
  53911. max = temp;
  53912. }
  53913. d = Math.max(min, d);
  53914. maxValue = Math.min(max, maxValue);
  53915. if (d > maxValue) {
  53916. return false;
  53917. }
  53918. }
  53919. if (Math.abs(this.direction.y) < 0.0000001) {
  53920. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53921. return false;
  53922. }
  53923. }
  53924. else {
  53925. inv = 1.0 / this.direction.y;
  53926. min = (minimum.y - this.origin.y) * inv;
  53927. max = (maximum.y - this.origin.y) * inv;
  53928. if (max === -Infinity) {
  53929. max = Infinity;
  53930. }
  53931. if (min > max) {
  53932. temp = min;
  53933. min = max;
  53934. max = temp;
  53935. }
  53936. d = Math.max(min, d);
  53937. maxValue = Math.min(max, maxValue);
  53938. if (d > maxValue) {
  53939. return false;
  53940. }
  53941. }
  53942. if (Math.abs(this.direction.z) < 0.0000001) {
  53943. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53944. return false;
  53945. }
  53946. }
  53947. else {
  53948. inv = 1.0 / this.direction.z;
  53949. min = (minimum.z - this.origin.z) * inv;
  53950. max = (maximum.z - this.origin.z) * inv;
  53951. if (max === -Infinity) {
  53952. max = Infinity;
  53953. }
  53954. if (min > max) {
  53955. temp = min;
  53956. min = max;
  53957. max = temp;
  53958. }
  53959. d = Math.max(min, d);
  53960. maxValue = Math.min(max, maxValue);
  53961. if (d > maxValue) {
  53962. return false;
  53963. }
  53964. }
  53965. return true;
  53966. };
  53967. Ray.prototype.intersectsBox = function (box) {
  53968. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53969. };
  53970. Ray.prototype.intersectsSphere = function (sphere) {
  53971. var x = sphere.center.x - this.origin.x;
  53972. var y = sphere.center.y - this.origin.y;
  53973. var z = sphere.center.z - this.origin.z;
  53974. var pyth = (x * x) + (y * y) + (z * z);
  53975. var rr = sphere.radius * sphere.radius;
  53976. if (pyth <= rr) {
  53977. return true;
  53978. }
  53979. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53980. if (dot < 0.0) {
  53981. return false;
  53982. }
  53983. var temp = pyth - (dot * dot);
  53984. return temp <= rr;
  53985. };
  53986. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53987. if (!this._edge1) {
  53988. this._edge1 = BABYLON.Vector3.Zero();
  53989. this._edge2 = BABYLON.Vector3.Zero();
  53990. this._pvec = BABYLON.Vector3.Zero();
  53991. this._tvec = BABYLON.Vector3.Zero();
  53992. this._qvec = BABYLON.Vector3.Zero();
  53993. }
  53994. vertex1.subtractToRef(vertex0, this._edge1);
  53995. vertex2.subtractToRef(vertex0, this._edge2);
  53996. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53997. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53998. if (det === 0) {
  53999. return null;
  54000. }
  54001. var invdet = 1 / det;
  54002. this.origin.subtractToRef(vertex0, this._tvec);
  54003. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54004. if (bu < 0 || bu > 1.0) {
  54005. return null;
  54006. }
  54007. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54008. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54009. if (bv < 0 || bu + bv > 1.0) {
  54010. return null;
  54011. }
  54012. //check if the distance is longer than the predefined length.
  54013. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54014. if (distance > this.length) {
  54015. return null;
  54016. }
  54017. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54018. };
  54019. Ray.prototype.intersectsPlane = function (plane) {
  54020. var distance;
  54021. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54022. if (Math.abs(result1) < 9.99999997475243E-07) {
  54023. return null;
  54024. }
  54025. else {
  54026. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54027. distance = (-plane.d - result2) / result1;
  54028. if (distance < 0.0) {
  54029. if (distance < -9.99999997475243E-07) {
  54030. return null;
  54031. }
  54032. else {
  54033. return 0;
  54034. }
  54035. }
  54036. return distance;
  54037. }
  54038. };
  54039. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54040. var tm = BABYLON.Tmp.Matrix[0];
  54041. mesh.getWorldMatrix().invertToRef(tm);
  54042. if (this._tmpRay) {
  54043. Ray.TransformToRef(this, tm, this._tmpRay);
  54044. }
  54045. else {
  54046. this._tmpRay = Ray.Transform(this, tm);
  54047. }
  54048. return mesh.intersects(this._tmpRay, fastCheck);
  54049. };
  54050. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54051. if (results) {
  54052. results.length = 0;
  54053. }
  54054. else {
  54055. results = [];
  54056. }
  54057. for (var i = 0; i < meshes.length; i++) {
  54058. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54059. if (pickInfo.hit) {
  54060. results.push(pickInfo);
  54061. }
  54062. }
  54063. results.sort(this._comparePickingInfo);
  54064. return results;
  54065. };
  54066. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54067. if (pickingInfoA.distance < pickingInfoB.distance) {
  54068. return -1;
  54069. }
  54070. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54071. return 1;
  54072. }
  54073. else {
  54074. return 0;
  54075. }
  54076. };
  54077. /**
  54078. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54079. * @param sega the first point of the segment to test the intersection against
  54080. * @param segb the second point of the segment to test the intersection against
  54081. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54082. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54083. */
  54084. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54085. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54086. var u = segb.subtract(sega);
  54087. var v = rsegb.subtract(this.origin);
  54088. var w = sega.subtract(this.origin);
  54089. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54090. var b = BABYLON.Vector3.Dot(u, v);
  54091. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54092. var d = BABYLON.Vector3.Dot(u, w);
  54093. var e = BABYLON.Vector3.Dot(v, w);
  54094. var D = a * c - b * b; // always >= 0
  54095. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54096. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54097. // compute the line parameters of the two closest points
  54098. if (D < Ray.smallnum) { // the lines are almost parallel
  54099. sN = 0.0; // force using point P0 on segment S1
  54100. sD = 1.0; // to prevent possible division by 0.0 later
  54101. tN = e;
  54102. tD = c;
  54103. }
  54104. else { // get the closest points on the infinite lines
  54105. sN = (b * e - c * d);
  54106. tN = (a * e - b * d);
  54107. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54108. sN = 0.0;
  54109. tN = e;
  54110. tD = c;
  54111. }
  54112. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54113. sN = sD;
  54114. tN = e + b;
  54115. tD = c;
  54116. }
  54117. }
  54118. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54119. tN = 0.0;
  54120. // recompute sc for this edge
  54121. if (-d < 0.0) {
  54122. sN = 0.0;
  54123. }
  54124. else if (-d > a)
  54125. sN = sD;
  54126. else {
  54127. sN = -d;
  54128. sD = a;
  54129. }
  54130. }
  54131. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54132. tN = tD;
  54133. // recompute sc for this edge
  54134. if ((-d + b) < 0.0) {
  54135. sN = 0;
  54136. }
  54137. else if ((-d + b) > a) {
  54138. sN = sD;
  54139. }
  54140. else {
  54141. sN = (-d + b);
  54142. sD = a;
  54143. }
  54144. }
  54145. // finally do the division to get sc and tc
  54146. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54147. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54148. // get the difference of the two closest points
  54149. var qtc = v.multiplyByFloats(tc, tc, tc);
  54150. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54151. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54152. if (isIntersected) {
  54153. return qtc.length();
  54154. }
  54155. return -1;
  54156. };
  54157. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54158. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54159. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54160. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54161. this.direction.normalize();
  54162. return this;
  54163. };
  54164. // Statics
  54165. Ray.Zero = function () {
  54166. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54167. };
  54168. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54169. var result = Ray.Zero();
  54170. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54171. };
  54172. /**
  54173. * 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
  54174. * transformed to the given world matrix.
  54175. * @param origin The origin point
  54176. * @param end The end point
  54177. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54178. */
  54179. Ray.CreateNewFromTo = function (origin, end, world) {
  54180. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54181. var direction = end.subtract(origin);
  54182. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54183. direction.normalize();
  54184. return Ray.Transform(new Ray(origin, direction, length), world);
  54185. };
  54186. Ray.Transform = function (ray, matrix) {
  54187. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54188. Ray.TransformToRef(ray, matrix, result);
  54189. return result;
  54190. };
  54191. Ray.TransformToRef = function (ray, matrix, result) {
  54192. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54193. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54194. result.length = ray.length;
  54195. var dir = result.direction;
  54196. var len = dir.length();
  54197. if (!(len === 0 || len === 1)) {
  54198. var num = 1.0 / len;
  54199. dir.x *= num;
  54200. dir.y *= num;
  54201. dir.z *= num;
  54202. result.length *= len;
  54203. }
  54204. };
  54205. Ray.smallnum = 0.00000001;
  54206. Ray.rayl = 10e8;
  54207. return Ray;
  54208. }());
  54209. BABYLON.Ray = Ray;
  54210. })(BABYLON || (BABYLON = {}));
  54211. //# sourceMappingURL=babylon.ray.js.map
  54212. var BABYLON;
  54213. (function (BABYLON) {
  54214. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54215. if (boxMin.x > sphereCenter.x + sphereRadius)
  54216. return false;
  54217. if (sphereCenter.x - sphereRadius > boxMax.x)
  54218. return false;
  54219. if (boxMin.y > sphereCenter.y + sphereRadius)
  54220. return false;
  54221. if (sphereCenter.y - sphereRadius > boxMax.y)
  54222. return false;
  54223. if (boxMin.z > sphereCenter.z + sphereRadius)
  54224. return false;
  54225. if (sphereCenter.z - sphereRadius > boxMax.z)
  54226. return false;
  54227. return true;
  54228. };
  54229. var getLowestRoot = (function () {
  54230. var result = { root: 0, found: false };
  54231. return function (a, b, c, maxR) {
  54232. result.root = 0;
  54233. result.found = false;
  54234. var determinant = b * b - 4.0 * a * c;
  54235. if (determinant < 0)
  54236. return result;
  54237. var sqrtD = Math.sqrt(determinant);
  54238. var r1 = (-b - sqrtD) / (2.0 * a);
  54239. var r2 = (-b + sqrtD) / (2.0 * a);
  54240. if (r1 > r2) {
  54241. var temp = r2;
  54242. r2 = r1;
  54243. r1 = temp;
  54244. }
  54245. if (r1 > 0 && r1 < maxR) {
  54246. result.root = r1;
  54247. result.found = true;
  54248. return result;
  54249. }
  54250. if (r2 > 0 && r2 < maxR) {
  54251. result.root = r2;
  54252. result.found = true;
  54253. return result;
  54254. }
  54255. return result;
  54256. };
  54257. })();
  54258. var Collider = /** @class */ (function () {
  54259. function Collider() {
  54260. this._collisionPoint = BABYLON.Vector3.Zero();
  54261. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54262. this._tempVector = BABYLON.Vector3.Zero();
  54263. this._tempVector2 = BABYLON.Vector3.Zero();
  54264. this._tempVector3 = BABYLON.Vector3.Zero();
  54265. this._tempVector4 = BABYLON.Vector3.Zero();
  54266. this._edge = BABYLON.Vector3.Zero();
  54267. this._baseToVertex = BABYLON.Vector3.Zero();
  54268. this._destinationPoint = BABYLON.Vector3.Zero();
  54269. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54270. this._displacementVector = BABYLON.Vector3.Zero();
  54271. this._radius = BABYLON.Vector3.One();
  54272. this._retry = 0;
  54273. this._basePointWorld = BABYLON.Vector3.Zero();
  54274. this._velocityWorld = BABYLON.Vector3.Zero();
  54275. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54276. this._collisionMask = -1;
  54277. }
  54278. Object.defineProperty(Collider.prototype, "collisionMask", {
  54279. get: function () {
  54280. return this._collisionMask;
  54281. },
  54282. set: function (mask) {
  54283. this._collisionMask = !isNaN(mask) ? mask : -1;
  54284. },
  54285. enumerable: true,
  54286. configurable: true
  54287. });
  54288. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54289. /**
  54290. * Gets the plane normal used to compute the sliding response (in local space)
  54291. */
  54292. get: function () {
  54293. return this._slidePlaneNormal;
  54294. },
  54295. enumerable: true,
  54296. configurable: true
  54297. });
  54298. // Methods
  54299. Collider.prototype._initialize = function (source, dir, e) {
  54300. this._velocity = dir;
  54301. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54302. this._basePoint = source;
  54303. source.multiplyToRef(this._radius, this._basePointWorld);
  54304. dir.multiplyToRef(this._radius, this._velocityWorld);
  54305. this._velocityWorldLength = this._velocityWorld.length();
  54306. this._epsilon = e;
  54307. this.collisionFound = false;
  54308. };
  54309. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54310. pa.subtractToRef(point, this._tempVector);
  54311. pb.subtractToRef(point, this._tempVector2);
  54312. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54313. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54314. if (d < 0)
  54315. return false;
  54316. pc.subtractToRef(point, this._tempVector3);
  54317. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54318. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54319. if (d < 0)
  54320. return false;
  54321. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54322. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54323. return d >= 0;
  54324. };
  54325. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54326. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54327. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54328. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54329. return false;
  54330. }
  54331. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54332. return false;
  54333. return true;
  54334. };
  54335. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54336. var t0;
  54337. var embeddedInPlane = false;
  54338. //defensive programming, actually not needed.
  54339. if (!trianglePlaneArray) {
  54340. trianglePlaneArray = [];
  54341. }
  54342. if (!trianglePlaneArray[faceIndex]) {
  54343. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54344. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54345. }
  54346. var trianglePlane = trianglePlaneArray[faceIndex];
  54347. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54348. return;
  54349. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54350. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54351. if (normalDotVelocity == 0) {
  54352. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54353. return;
  54354. embeddedInPlane = true;
  54355. t0 = 0;
  54356. }
  54357. else {
  54358. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54359. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54360. if (t0 > t1) {
  54361. var temp = t1;
  54362. t1 = t0;
  54363. t0 = temp;
  54364. }
  54365. if (t0 > 1.0 || t1 < 0.0)
  54366. return;
  54367. if (t0 < 0)
  54368. t0 = 0;
  54369. if (t0 > 1.0)
  54370. t0 = 1.0;
  54371. }
  54372. this._collisionPoint.copyFromFloats(0, 0, 0);
  54373. var found = false;
  54374. var t = 1.0;
  54375. if (!embeddedInPlane) {
  54376. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54377. this._velocity.scaleToRef(t0, this._tempVector);
  54378. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54379. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54380. found = true;
  54381. t = t0;
  54382. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54383. }
  54384. }
  54385. if (!found) {
  54386. var velocitySquaredLength = this._velocity.lengthSquared();
  54387. var a = velocitySquaredLength;
  54388. this._basePoint.subtractToRef(p1, this._tempVector);
  54389. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54390. var c = this._tempVector.lengthSquared() - 1.0;
  54391. var lowestRoot = getLowestRoot(a, b, c, t);
  54392. if (lowestRoot.found) {
  54393. t = lowestRoot.root;
  54394. found = true;
  54395. this._collisionPoint.copyFrom(p1);
  54396. }
  54397. this._basePoint.subtractToRef(p2, this._tempVector);
  54398. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54399. c = this._tempVector.lengthSquared() - 1.0;
  54400. lowestRoot = getLowestRoot(a, b, c, t);
  54401. if (lowestRoot.found) {
  54402. t = lowestRoot.root;
  54403. found = true;
  54404. this._collisionPoint.copyFrom(p2);
  54405. }
  54406. this._basePoint.subtractToRef(p3, this._tempVector);
  54407. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54408. c = this._tempVector.lengthSquared() - 1.0;
  54409. lowestRoot = getLowestRoot(a, b, c, t);
  54410. if (lowestRoot.found) {
  54411. t = lowestRoot.root;
  54412. found = true;
  54413. this._collisionPoint.copyFrom(p3);
  54414. }
  54415. p2.subtractToRef(p1, this._edge);
  54416. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54417. var edgeSquaredLength = this._edge.lengthSquared();
  54418. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54419. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54420. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54421. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54422. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54423. lowestRoot = getLowestRoot(a, b, c, t);
  54424. if (lowestRoot.found) {
  54425. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54426. if (f >= 0.0 && f <= 1.0) {
  54427. t = lowestRoot.root;
  54428. found = true;
  54429. this._edge.scaleInPlace(f);
  54430. p1.addToRef(this._edge, this._collisionPoint);
  54431. }
  54432. }
  54433. p3.subtractToRef(p2, this._edge);
  54434. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54435. edgeSquaredLength = this._edge.lengthSquared();
  54436. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54437. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54438. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54439. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54440. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54441. lowestRoot = getLowestRoot(a, b, c, t);
  54442. if (lowestRoot.found) {
  54443. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54444. if (f >= 0.0 && f <= 1.0) {
  54445. t = lowestRoot.root;
  54446. found = true;
  54447. this._edge.scaleInPlace(f);
  54448. p2.addToRef(this._edge, this._collisionPoint);
  54449. }
  54450. }
  54451. p1.subtractToRef(p3, this._edge);
  54452. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54453. edgeSquaredLength = this._edge.lengthSquared();
  54454. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54455. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54456. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54457. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54458. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54459. lowestRoot = getLowestRoot(a, b, c, t);
  54460. if (lowestRoot.found) {
  54461. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54462. if (f >= 0.0 && f <= 1.0) {
  54463. t = lowestRoot.root;
  54464. found = true;
  54465. this._edge.scaleInPlace(f);
  54466. p3.addToRef(this._edge, this._collisionPoint);
  54467. }
  54468. }
  54469. }
  54470. if (found) {
  54471. var distToCollision = t * this._velocity.length();
  54472. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54473. if (!this.intersectionPoint) {
  54474. this.intersectionPoint = this._collisionPoint.clone();
  54475. }
  54476. else {
  54477. this.intersectionPoint.copyFrom(this._collisionPoint);
  54478. }
  54479. this._nearestDistance = distToCollision;
  54480. this.collisionFound = true;
  54481. }
  54482. }
  54483. };
  54484. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54485. for (var i = indexStart; i < indexEnd; i += 3) {
  54486. var p1 = pts[indices[i] - decal];
  54487. var p2 = pts[indices[i + 1] - decal];
  54488. var p3 = pts[indices[i + 2] - decal];
  54489. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54490. }
  54491. };
  54492. Collider.prototype._getResponse = function (pos, vel) {
  54493. pos.addToRef(vel, this._destinationPoint);
  54494. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54495. this._basePoint.addToRef(vel, pos);
  54496. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54497. this._slidePlaneNormal.normalize();
  54498. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54499. pos.addInPlace(this._displacementVector);
  54500. this.intersectionPoint.addInPlace(this._displacementVector);
  54501. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54502. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54503. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54504. };
  54505. return Collider;
  54506. }());
  54507. BABYLON.Collider = Collider;
  54508. })(BABYLON || (BABYLON = {}));
  54509. //# sourceMappingURL=babylon.collider.js.map
  54510. var BABYLON;
  54511. (function (BABYLON) {
  54512. //WebWorker code will be inserted to this variable.
  54513. BABYLON.CollisionWorker = "";
  54514. /** Defines supported task for worker process */
  54515. var WorkerTaskType;
  54516. (function (WorkerTaskType) {
  54517. /** Initialization */
  54518. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54519. /** Update of geometry */
  54520. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54521. /** Evaluate collision */
  54522. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54523. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54524. /** Defines kind of replies returned by worker */
  54525. var WorkerReplyType;
  54526. (function (WorkerReplyType) {
  54527. /** Success */
  54528. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54529. /** Unkown error */
  54530. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54531. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54532. var CollisionCoordinatorWorker = /** @class */ (function () {
  54533. function CollisionCoordinatorWorker() {
  54534. var _this = this;
  54535. this._scaledPosition = BABYLON.Vector3.Zero();
  54536. this._scaledVelocity = BABYLON.Vector3.Zero();
  54537. this.onMeshUpdated = function (transformNode) {
  54538. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54539. };
  54540. this.onGeometryUpdated = function (geometry) {
  54541. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54542. };
  54543. this._afterRender = function () {
  54544. if (!_this._init)
  54545. return;
  54546. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54547. return;
  54548. }
  54549. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54550. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54551. if (_this._runningUpdated > 4) {
  54552. return;
  54553. }
  54554. ++_this._runningUpdated;
  54555. var payload = {
  54556. updatedMeshes: _this._addUpdateMeshesList,
  54557. updatedGeometries: _this._addUpdateGeometriesList,
  54558. removedGeometries: _this._toRemoveGeometryArray,
  54559. removedMeshes: _this._toRemoveMeshesArray
  54560. };
  54561. var message = {
  54562. payload: payload,
  54563. taskType: WorkerTaskType.UPDATE
  54564. };
  54565. var serializable = [];
  54566. for (var id in payload.updatedGeometries) {
  54567. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54568. //prepare transferables
  54569. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54570. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54571. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54572. }
  54573. }
  54574. _this._worker.postMessage(message, serializable);
  54575. _this._addUpdateMeshesList = {};
  54576. _this._addUpdateGeometriesList = {};
  54577. _this._toRemoveGeometryArray = [];
  54578. _this._toRemoveMeshesArray = [];
  54579. };
  54580. this._onMessageFromWorker = function (e) {
  54581. var returnData = e.data;
  54582. if (returnData.error != WorkerReplyType.SUCCESS) {
  54583. //TODO what errors can be returned from the worker?
  54584. BABYLON.Tools.Warn("error returned from worker!");
  54585. return;
  54586. }
  54587. switch (returnData.taskType) {
  54588. case WorkerTaskType.INIT:
  54589. _this._init = true;
  54590. //Update the worked with ALL of the scene's current state
  54591. _this._scene.meshes.forEach(function (mesh) {
  54592. _this.onMeshAdded(mesh);
  54593. });
  54594. _this._scene.getGeometries().forEach(function (geometry) {
  54595. _this.onGeometryAdded(geometry);
  54596. });
  54597. break;
  54598. case WorkerTaskType.UPDATE:
  54599. _this._runningUpdated--;
  54600. break;
  54601. case WorkerTaskType.COLLIDE:
  54602. var returnPayload = returnData.payload;
  54603. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54604. return;
  54605. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54606. if (callback) {
  54607. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54608. if (mesh) {
  54609. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54610. }
  54611. }
  54612. //cleanup
  54613. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54614. break;
  54615. }
  54616. };
  54617. this._collisionsCallbackArray = [];
  54618. this._init = false;
  54619. this._runningUpdated = 0;
  54620. this._addUpdateMeshesList = {};
  54621. this._addUpdateGeometriesList = {};
  54622. this._toRemoveGeometryArray = [];
  54623. this._toRemoveMeshesArray = [];
  54624. }
  54625. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54626. if (!this._init)
  54627. return;
  54628. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54629. return;
  54630. position.divideToRef(collider._radius, this._scaledPosition);
  54631. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54632. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54633. var payload = {
  54634. collider: {
  54635. position: this._scaledPosition.asArray(),
  54636. velocity: this._scaledVelocity.asArray(),
  54637. radius: collider._radius.asArray()
  54638. },
  54639. collisionId: collisionIndex,
  54640. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54641. maximumRetry: maximumRetry
  54642. };
  54643. var message = {
  54644. payload: payload,
  54645. taskType: WorkerTaskType.COLLIDE
  54646. };
  54647. this._worker.postMessage(message);
  54648. };
  54649. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54650. this._scene = scene;
  54651. this._scene.registerAfterRender(this._afterRender);
  54652. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54653. this._worker = new Worker(workerUrl);
  54654. this._worker.onmessage = this._onMessageFromWorker;
  54655. var message = {
  54656. payload: {},
  54657. taskType: WorkerTaskType.INIT
  54658. };
  54659. this._worker.postMessage(message);
  54660. };
  54661. CollisionCoordinatorWorker.prototype.destroy = function () {
  54662. this._scene.unregisterAfterRender(this._afterRender);
  54663. this._worker.terminate();
  54664. };
  54665. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54666. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54667. this.onMeshUpdated(mesh);
  54668. };
  54669. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54670. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54671. };
  54672. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54673. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54674. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54675. this.onGeometryUpdated(geometry);
  54676. };
  54677. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54678. this._toRemoveGeometryArray.push(geometry.id);
  54679. };
  54680. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54681. var submeshes = [];
  54682. if (mesh.subMeshes) {
  54683. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54684. var boundingInfo = sm.getBoundingInfo();
  54685. return {
  54686. position: idx,
  54687. verticesStart: sm.verticesStart,
  54688. verticesCount: sm.verticesCount,
  54689. indexStart: sm.indexStart,
  54690. indexCount: sm.indexCount,
  54691. hasMaterial: !!sm.getMaterial(),
  54692. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54693. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54694. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54695. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54696. };
  54697. });
  54698. }
  54699. var geometryId = null;
  54700. if (mesh instanceof BABYLON.Mesh) {
  54701. var geometry = mesh.geometry;
  54702. geometryId = geometry ? geometry.id : null;
  54703. }
  54704. else if (mesh instanceof BABYLON.InstancedMesh) {
  54705. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54706. geometryId = geometry ? geometry.id : null;
  54707. }
  54708. var boundingInfo = mesh.getBoundingInfo();
  54709. return {
  54710. uniqueId: mesh.uniqueId,
  54711. id: mesh.id,
  54712. name: mesh.name,
  54713. geometryId: geometryId,
  54714. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54715. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54716. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54717. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54718. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54719. subMeshes: submeshes,
  54720. checkCollisions: mesh.checkCollisions
  54721. };
  54722. };
  54723. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54724. return {
  54725. id: geometry.id,
  54726. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54727. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54728. indices: new Uint32Array(geometry.getIndices() || []),
  54729. };
  54730. };
  54731. return CollisionCoordinatorWorker;
  54732. }());
  54733. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54734. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54735. function CollisionCoordinatorLegacy() {
  54736. this._scaledPosition = BABYLON.Vector3.Zero();
  54737. this._scaledVelocity = BABYLON.Vector3.Zero();
  54738. this._finalPosition = BABYLON.Vector3.Zero();
  54739. }
  54740. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54741. position.divideToRef(collider._radius, this._scaledPosition);
  54742. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54743. collider.collidedMesh = null;
  54744. collider._retry = 0;
  54745. collider._initialVelocity = this._scaledVelocity;
  54746. collider._initialPosition = this._scaledPosition;
  54747. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54748. this._finalPosition.multiplyInPlace(collider._radius);
  54749. //run the callback
  54750. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54751. };
  54752. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54753. this._scene = scene;
  54754. };
  54755. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54756. //Legacy need no destruction method.
  54757. };
  54758. //No update in legacy mode
  54759. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54760. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54761. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54762. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54763. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54764. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54765. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54766. if (excludedMesh === void 0) { excludedMesh = null; }
  54767. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54768. if (collider._retry >= maximumRetry) {
  54769. finalPosition.copyFrom(position);
  54770. return;
  54771. }
  54772. // Check if this is a mesh else camera or -1
  54773. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54774. collider._initialize(position, velocity, closeDistance);
  54775. // Check all meshes
  54776. for (var index = 0; index < this._scene.meshes.length; index++) {
  54777. var mesh = this._scene.meshes[index];
  54778. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54779. mesh._checkCollision(collider);
  54780. }
  54781. }
  54782. if (!collider.collisionFound) {
  54783. position.addToRef(velocity, finalPosition);
  54784. return;
  54785. }
  54786. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54787. collider._getResponse(position, velocity);
  54788. }
  54789. if (velocity.length() <= closeDistance) {
  54790. finalPosition.copyFrom(position);
  54791. return;
  54792. }
  54793. collider._retry++;
  54794. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54795. };
  54796. return CollisionCoordinatorLegacy;
  54797. }());
  54798. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54799. })(BABYLON || (BABYLON = {}));
  54800. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54801. var BABYLON;
  54802. (function (BABYLON) {
  54803. /**
  54804. * A particle represents one of the element emitted by a particle system.
  54805. * This is mainly define by its coordinates, direction, velocity and age.
  54806. */
  54807. var Particle = /** @class */ (function () {
  54808. /**
  54809. * Creates a new instance Particle
  54810. * @param particleSystem the particle system the particle belongs to
  54811. */
  54812. function Particle(
  54813. /**
  54814. * particleSystem the particle system the particle belongs to.
  54815. */
  54816. particleSystem) {
  54817. this.particleSystem = particleSystem;
  54818. /**
  54819. * The world position of the particle in the scene.
  54820. */
  54821. this.position = BABYLON.Vector3.Zero();
  54822. /**
  54823. * The world direction of the particle in the scene.
  54824. */
  54825. this.direction = BABYLON.Vector3.Zero();
  54826. /**
  54827. * The color of the particle.
  54828. */
  54829. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54830. /**
  54831. * The color change of the particle per step.
  54832. */
  54833. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54834. /**
  54835. * Defines how long will the life of the particle be.
  54836. */
  54837. this.lifeTime = 1.0;
  54838. /**
  54839. * The current age of the particle.
  54840. */
  54841. this.age = 0;
  54842. /**
  54843. * The current size of the particle.
  54844. */
  54845. this.size = 0;
  54846. /**
  54847. * The current scale of the particle.
  54848. */
  54849. this.scale = new BABYLON.Vector2(1, 1);
  54850. /**
  54851. * The current angle of the particle.
  54852. */
  54853. this.angle = 0;
  54854. /**
  54855. * Defines how fast is the angle changing.
  54856. */
  54857. this.angularSpeed = 0;
  54858. /**
  54859. * Defines the cell index used by the particle to be rendered from a sprite.
  54860. */
  54861. this.cellIndex = 0;
  54862. /** @hidden */
  54863. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54864. /** @hidden */
  54865. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54866. /** @hidden */
  54867. this._currentSize1 = 0;
  54868. /** @hidden */
  54869. this._currentSize2 = 0;
  54870. if (!this.particleSystem.isAnimationSheetEnabled) {
  54871. return;
  54872. }
  54873. this.updateCellInfoFromSystem();
  54874. }
  54875. Particle.prototype.updateCellInfoFromSystem = function () {
  54876. this.cellIndex = this.particleSystem.startSpriteCellID;
  54877. };
  54878. /**
  54879. * Defines how the sprite cell index is updated for the particle
  54880. */
  54881. Particle.prototype.updateCellIndex = function () {
  54882. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54883. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54884. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54885. };
  54886. /**
  54887. * Copy the properties of particle to another one.
  54888. * @param other the particle to copy the information to.
  54889. */
  54890. Particle.prototype.copyTo = function (other) {
  54891. other.position.copyFrom(this.position);
  54892. if (this._initialDirection) {
  54893. if (other._initialDirection) {
  54894. other._initialDirection.copyFrom(this._initialDirection);
  54895. }
  54896. else {
  54897. other._initialDirection = this._initialDirection.clone();
  54898. }
  54899. }
  54900. else {
  54901. other._initialDirection = null;
  54902. }
  54903. other.direction.copyFrom(this.direction);
  54904. other.color.copyFrom(this.color);
  54905. other.colorStep.copyFrom(this.colorStep);
  54906. other.lifeTime = this.lifeTime;
  54907. other.age = this.age;
  54908. other.size = this.size;
  54909. other.scale.copyFrom(this.scale);
  54910. other.angle = this.angle;
  54911. other.angularSpeed = this.angularSpeed;
  54912. other.particleSystem = this.particleSystem;
  54913. other.cellIndex = this.cellIndex;
  54914. if (this._currentColorGradient) {
  54915. other._currentColorGradient = this._currentColorGradient;
  54916. other._currentColor1.copyFrom(this._currentColor1);
  54917. other._currentColor2.copyFrom(this._currentColor2);
  54918. }
  54919. if (this._currentSizeGradient) {
  54920. other._currentSizeGradient = this._currentSizeGradient;
  54921. other._currentSize1 = this._currentSize1;
  54922. other._currentSize2 = this._currentSize2;
  54923. }
  54924. if (this.particleSystem.isAnimationSheetEnabled) {
  54925. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54926. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54927. }
  54928. };
  54929. return Particle;
  54930. }());
  54931. BABYLON.Particle = Particle;
  54932. })(BABYLON || (BABYLON = {}));
  54933. //# sourceMappingURL=babylon.particle.js.map
  54934. var BABYLON;
  54935. (function (BABYLON) {
  54936. /**
  54937. * This represents a particle system in Babylon.
  54938. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  54939. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54940. * @example https://doc.babylonjs.com/babylon101/particles
  54941. */
  54942. var ParticleSystem = /** @class */ (function () {
  54943. /**
  54944. * Instantiates a particle system.
  54945. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  54946. * @param name The name of the particle system
  54947. * @param capacity The max number of particles alive at the same time
  54948. * @param scene The scene the particle system belongs to
  54949. * @param customEffect a custom effect used to change the way particles are rendered by default
  54950. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54951. * @param epsilon Offset used to render the particles
  54952. */
  54953. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54954. if (customEffect === void 0) { customEffect = null; }
  54955. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54956. if (epsilon === void 0) { epsilon = 0.01; }
  54957. var _this = this;
  54958. /**
  54959. * List of animations used by the particle system.
  54960. */
  54961. this.animations = [];
  54962. /**
  54963. * The rendering group used by the Particle system to chose when to render.
  54964. */
  54965. this.renderingGroupId = 0;
  54966. /**
  54967. * The emitter represents the Mesh or position we are attaching the particle system to.
  54968. */
  54969. this.emitter = null;
  54970. /**
  54971. * The maximum number of particles to emit per frame
  54972. */
  54973. this.emitRate = 10;
  54974. /**
  54975. * If you want to launch only a few particles at once, that can be done, as well.
  54976. */
  54977. this.manualEmitCount = -1;
  54978. /**
  54979. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54980. */
  54981. this.updateSpeed = 0.01;
  54982. /**
  54983. * The amount of time the particle system is running (depends of the overall update speed).
  54984. */
  54985. this.targetStopDuration = 0;
  54986. /**
  54987. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54988. */
  54989. this.disposeOnStop = false;
  54990. /**
  54991. * Minimum power of emitting particles.
  54992. */
  54993. this.minEmitPower = 1;
  54994. /**
  54995. * Maximum power of emitting particles.
  54996. */
  54997. this.maxEmitPower = 1;
  54998. /**
  54999. * Minimum life time of emitting particles.
  55000. */
  55001. this.minLifeTime = 1;
  55002. /**
  55003. * Maximum life time of emitting particles.
  55004. */
  55005. this.maxLifeTime = 1;
  55006. /**
  55007. * Minimum Size of emitting particles.
  55008. */
  55009. this.minSize = 1;
  55010. /**
  55011. * Maximum Size of emitting particles.
  55012. */
  55013. this.maxSize = 1;
  55014. /**
  55015. * Minimum scale of emitting particles on X axis.
  55016. */
  55017. this.minScaleX = 1;
  55018. /**
  55019. * Maximum scale of emitting particles on X axis.
  55020. */
  55021. this.maxScaleX = 1;
  55022. /**
  55023. * Minimum scale of emitting particles on Y axis.
  55024. */
  55025. this.minScaleY = 1;
  55026. /**
  55027. * Maximum scale of emitting particles on Y axis.
  55028. */
  55029. this.maxScaleY = 1;
  55030. /**
  55031. * Gets or sets the minimal initial rotation in radians.
  55032. */
  55033. this.minInitialRotation = 0;
  55034. /**
  55035. * Gets or sets the maximal initial rotation in radians.
  55036. */
  55037. this.maxInitialRotation = 0;
  55038. /**
  55039. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55040. */
  55041. this.minAngularSpeed = 0;
  55042. /**
  55043. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55044. */
  55045. this.maxAngularSpeed = 0;
  55046. /**
  55047. * The layer mask we are rendering the particles through.
  55048. */
  55049. this.layerMask = 0x0FFFFFFF;
  55050. /**
  55051. * This can help using your own shader to render the particle system.
  55052. * The according effect will be created
  55053. */
  55054. this.customShader = null;
  55055. /**
  55056. * By default particle system starts as soon as they are created. This prevents the
  55057. * automatic start to happen and let you decide when to start emitting particles.
  55058. */
  55059. this.preventAutoStart = false;
  55060. /**
  55061. * Callback triggered when the particle animation is ending.
  55062. */
  55063. this.onAnimationEnd = null;
  55064. /**
  55065. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55066. */
  55067. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55068. /**
  55069. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55070. * to override the particles.
  55071. */
  55072. this.forceDepthWrite = false;
  55073. /**
  55074. * You can use gravity if you want to give an orientation to your particles.
  55075. */
  55076. this.gravity = BABYLON.Vector3.Zero();
  55077. this._colorGradients = null;
  55078. this._sizeGradients = null;
  55079. this._lifeTimeGradients = null;
  55080. /**
  55081. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55082. */
  55083. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55084. /**
  55085. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55086. */
  55087. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55088. /**
  55089. * Color the particle will have at the end of its lifetime
  55090. */
  55091. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55092. /**
  55093. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55094. */
  55095. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55096. /**
  55097. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55098. */
  55099. this.spriteCellChangeSpeed = 1;
  55100. /**
  55101. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55102. */
  55103. this.startSpriteCellID = 0;
  55104. /**
  55105. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55106. */
  55107. this.endSpriteCellID = 0;
  55108. /**
  55109. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55110. */
  55111. this.spriteCellWidth = 0;
  55112. /**
  55113. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55114. */
  55115. this.spriteCellHeight = 0;
  55116. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55117. this.preWarmCycles = 0;
  55118. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55119. this.preWarmStepOffset = 1;
  55120. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55121. this.translationPivot = new BABYLON.Vector2(0, 0);
  55122. /**
  55123. * An event triggered when the system is disposed
  55124. */
  55125. this.onDisposeObservable = new BABYLON.Observable();
  55126. /**
  55127. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55128. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55129. */
  55130. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55131. this._particles = new Array();
  55132. this._stockParticles = new Array();
  55133. this._newPartsExcess = 0;
  55134. this._vertexBuffers = {};
  55135. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55136. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55137. this._scaledDirection = BABYLON.Vector3.Zero();
  55138. this._scaledGravity = BABYLON.Vector3.Zero();
  55139. this._currentRenderId = -1;
  55140. this._useInstancing = false;
  55141. this._started = false;
  55142. this._stopped = false;
  55143. this._actualFrame = 0;
  55144. this._isBillboardBased = true;
  55145. // start of sub system methods
  55146. /**
  55147. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55148. * Its lifetime will start back at 0.
  55149. */
  55150. this.recycleParticle = function (particle) {
  55151. var lastParticle = _this._particles.pop();
  55152. if (lastParticle !== particle) {
  55153. lastParticle.copyTo(particle);
  55154. }
  55155. _this._stockParticles.push(lastParticle);
  55156. };
  55157. this._createParticle = function () {
  55158. var particle;
  55159. if (_this._stockParticles.length !== 0) {
  55160. particle = _this._stockParticles.pop();
  55161. particle.age = 0;
  55162. particle._currentColorGradient = null;
  55163. particle.cellIndex = _this.startSpriteCellID;
  55164. }
  55165. else {
  55166. particle = new BABYLON.Particle(_this);
  55167. }
  55168. return particle;
  55169. };
  55170. this._emitFromParticle = function (particle) {
  55171. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55172. return;
  55173. }
  55174. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55175. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55176. subSystem._rootParticleSystem = _this;
  55177. _this.activeSubSystems.push(subSystem);
  55178. subSystem.start();
  55179. };
  55180. this.id = name;
  55181. this.name = name;
  55182. this._capacity = capacity;
  55183. this._epsilon = epsilon;
  55184. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55185. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55186. this._customEffect = customEffect;
  55187. scene.particleSystems.push(this);
  55188. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55189. this._createIndexBuffer();
  55190. this._createVertexBuffers();
  55191. // Default emitter type
  55192. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55193. this.updateFunction = function (particles) {
  55194. for (var index = 0; index < particles.length; index++) {
  55195. var particle = particles[index];
  55196. particle.age += _this._scaledUpdateSpeed;
  55197. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55198. _this._emitFromParticle(particle);
  55199. _this.recycleParticle(particle);
  55200. index--;
  55201. continue;
  55202. }
  55203. else {
  55204. var ratio = particle.age / particle.lifeTime;
  55205. // Color
  55206. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55207. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55208. if (currentGradient !== particle._currentColorGradient) {
  55209. particle._currentColor1.copyFrom(particle._currentColor2);
  55210. nextGradient.getColorToRef(particle._currentColor2);
  55211. particle._currentColorGradient = currentGradient;
  55212. }
  55213. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55214. });
  55215. }
  55216. else {
  55217. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55218. particle.color.addInPlace(_this._scaledColorStep);
  55219. if (particle.color.a < 0) {
  55220. particle.color.a = 0;
  55221. }
  55222. }
  55223. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55224. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55225. particle.position.addInPlace(_this._scaledDirection);
  55226. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55227. particle.direction.addInPlace(_this._scaledGravity);
  55228. // Gradient
  55229. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55230. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55231. if (currentGradient !== particle._currentSizeGradient) {
  55232. particle._currentSize1 = particle._currentSize2;
  55233. particle._currentSize2 = nextGradient.getFactor();
  55234. particle._currentSizeGradient = currentGradient;
  55235. }
  55236. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55237. });
  55238. }
  55239. if (_this._isAnimationSheetEnabled) {
  55240. particle.updateCellIndex();
  55241. }
  55242. }
  55243. }
  55244. };
  55245. }
  55246. /**
  55247. * Gets the current list of color gradients.
  55248. * You must use addColorGradient and removeColorGradient to udpate this list
  55249. * @returns the list of color gradients
  55250. */
  55251. ParticleSystem.prototype.getColorGradients = function () {
  55252. return this._colorGradients;
  55253. };
  55254. /**
  55255. * Gets the current list of size gradients.
  55256. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55257. * @returns the list of size gradients
  55258. */
  55259. ParticleSystem.prototype.getSizeGradients = function () {
  55260. return this._sizeGradients;
  55261. };
  55262. /**
  55263. * Gets the current list of life time gradients.
  55264. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55265. * @returns the list of life time gradients
  55266. */
  55267. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55268. return this._lifeTimeGradients;
  55269. };
  55270. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55271. /**
  55272. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55273. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55274. */
  55275. get: function () {
  55276. if (this.particleEmitterType.direction1) {
  55277. return this.particleEmitterType.direction1;
  55278. }
  55279. return BABYLON.Vector3.Zero();
  55280. },
  55281. set: function (value) {
  55282. if (this.particleEmitterType.direction1) {
  55283. this.particleEmitterType.direction1 = value;
  55284. }
  55285. },
  55286. enumerable: true,
  55287. configurable: true
  55288. });
  55289. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55290. /**
  55291. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55292. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55293. */
  55294. get: function () {
  55295. if (this.particleEmitterType.direction2) {
  55296. return this.particleEmitterType.direction2;
  55297. }
  55298. return BABYLON.Vector3.Zero();
  55299. },
  55300. set: function (value) {
  55301. if (this.particleEmitterType.direction2) {
  55302. this.particleEmitterType.direction2 = value;
  55303. }
  55304. },
  55305. enumerable: true,
  55306. configurable: true
  55307. });
  55308. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55309. /**
  55310. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  55311. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55312. */
  55313. get: function () {
  55314. if (this.particleEmitterType.minEmitBox) {
  55315. return this.particleEmitterType.minEmitBox;
  55316. }
  55317. return BABYLON.Vector3.Zero();
  55318. },
  55319. set: function (value) {
  55320. if (this.particleEmitterType.minEmitBox) {
  55321. this.particleEmitterType.minEmitBox = value;
  55322. }
  55323. },
  55324. enumerable: true,
  55325. configurable: true
  55326. });
  55327. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55328. /**
  55329. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  55330. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55331. */
  55332. get: function () {
  55333. if (this.particleEmitterType.maxEmitBox) {
  55334. return this.particleEmitterType.maxEmitBox;
  55335. }
  55336. return BABYLON.Vector3.Zero();
  55337. },
  55338. set: function (value) {
  55339. if (this.particleEmitterType.maxEmitBox) {
  55340. this.particleEmitterType.maxEmitBox = value;
  55341. }
  55342. },
  55343. enumerable: true,
  55344. configurable: true
  55345. });
  55346. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55347. /**
  55348. * Sets a callback that will be triggered when the system is disposed
  55349. */
  55350. set: function (callback) {
  55351. if (this._onDisposeObserver) {
  55352. this.onDisposeObservable.remove(this._onDisposeObserver);
  55353. }
  55354. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55355. },
  55356. enumerable: true,
  55357. configurable: true
  55358. });
  55359. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55360. /**
  55361. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55362. */
  55363. get: function () {
  55364. return this._isAnimationSheetEnabled;
  55365. },
  55366. enumerable: true,
  55367. configurable: true
  55368. });
  55369. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55370. /**
  55371. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55372. */
  55373. get: function () {
  55374. return this._isBillboardBased;
  55375. },
  55376. set: function (value) {
  55377. if (this._isBillboardBased === value) {
  55378. return;
  55379. }
  55380. this._isBillboardBased = value;
  55381. this._resetEffect();
  55382. },
  55383. enumerable: true,
  55384. configurable: true
  55385. });
  55386. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55387. //end of Sub-emitter
  55388. /**
  55389. * Gets the current list of active particles
  55390. */
  55391. get: function () {
  55392. return this._particles;
  55393. },
  55394. enumerable: true,
  55395. configurable: true
  55396. });
  55397. /**
  55398. * Returns the string "ParticleSystem"
  55399. * @returns a string containing the class name
  55400. */
  55401. ParticleSystem.prototype.getClassName = function () {
  55402. return "ParticleSystem";
  55403. };
  55404. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55405. var newGradient = new BABYLON.FactorGradient();
  55406. newGradient.gradient = gradient;
  55407. newGradient.factor1 = factor;
  55408. newGradient.factor2 = factor2;
  55409. factorGradients.push(newGradient);
  55410. factorGradients.sort(function (a, b) {
  55411. if (a.gradient < b.gradient) {
  55412. return -1;
  55413. }
  55414. else if (a.gradient > b.gradient) {
  55415. return 1;
  55416. }
  55417. return 0;
  55418. });
  55419. };
  55420. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55421. if (!factorGradients) {
  55422. return;
  55423. }
  55424. var index = 0;
  55425. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55426. var factorGradient = factorGradients_1[_i];
  55427. if (factorGradient.gradient === gradient) {
  55428. factorGradients.splice(index, 1);
  55429. break;
  55430. }
  55431. index++;
  55432. }
  55433. };
  55434. /**
  55435. * Adds a new life time gradient
  55436. * @param gradient defines the gradient to use (between 0 and 1)
  55437. * @param factor defines the life time factor to affect to the specified gradient
  55438. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55439. */
  55440. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55441. if (!this._lifeTimeGradients) {
  55442. this._lifeTimeGradients = [];
  55443. }
  55444. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55445. return this;
  55446. };
  55447. /**
  55448. * Remove a specific life time gradient
  55449. * @param gradient defines the gradient to remove
  55450. */
  55451. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55452. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55453. return this;
  55454. };
  55455. /**
  55456. * Adds a new size gradient
  55457. * @param gradient defines the gradient to use (between 0 and 1)
  55458. * @param factor defines the size factor to affect to the specified gradient
  55459. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55460. */
  55461. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55462. if (!this._sizeGradients) {
  55463. this._sizeGradients = [];
  55464. }
  55465. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55466. return this;
  55467. };
  55468. /**
  55469. * Remove a specific size gradient
  55470. * @param gradient defines the gradient to remove
  55471. */
  55472. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55473. this._removeFactorGradient(this._sizeGradients, gradient);
  55474. return this;
  55475. };
  55476. /**
  55477. * Adds a new color gradient
  55478. * @param gradient defines the gradient to use (between 0 and 1)
  55479. * @param color defines the color to affect to the specified gradient
  55480. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55481. */
  55482. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55483. if (!this._colorGradients) {
  55484. this._colorGradients = [];
  55485. }
  55486. var colorGradient = new BABYLON.ColorGradient();
  55487. colorGradient.gradient = gradient;
  55488. colorGradient.color1 = color;
  55489. colorGradient.color2 = color2;
  55490. this._colorGradients.push(colorGradient);
  55491. this._colorGradients.sort(function (a, b) {
  55492. if (a.gradient < b.gradient) {
  55493. return -1;
  55494. }
  55495. else if (a.gradient > b.gradient) {
  55496. return 1;
  55497. }
  55498. return 0;
  55499. });
  55500. return this;
  55501. };
  55502. /**
  55503. * Remove a specific color gradient
  55504. * @param gradient defines the gradient to remove
  55505. */
  55506. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55507. if (!this._colorGradients) {
  55508. return this;
  55509. }
  55510. var index = 0;
  55511. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55512. var colorGradient = _a[_i];
  55513. if (colorGradient.gradient === gradient) {
  55514. this._colorGradients.splice(index, 1);
  55515. break;
  55516. }
  55517. index++;
  55518. }
  55519. return this;
  55520. };
  55521. ParticleSystem.prototype._resetEffect = function () {
  55522. if (this._vertexBuffer) {
  55523. this._vertexBuffer.dispose();
  55524. this._vertexBuffer = null;
  55525. }
  55526. if (this._spriteBuffer) {
  55527. this._spriteBuffer.dispose();
  55528. this._spriteBuffer = null;
  55529. }
  55530. this._createVertexBuffers();
  55531. };
  55532. ParticleSystem.prototype._createVertexBuffers = function () {
  55533. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55534. if (this._isAnimationSheetEnabled) {
  55535. this._vertexBufferSize += 1;
  55536. }
  55537. if (!this._isBillboardBased) {
  55538. this._vertexBufferSize += 3;
  55539. }
  55540. var engine = this._scene.getEngine();
  55541. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55542. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55543. var dataOffset = 0;
  55544. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55545. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55546. dataOffset += 3;
  55547. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55548. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55549. dataOffset += 4;
  55550. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55551. this._vertexBuffers["angle"] = options;
  55552. dataOffset += 1;
  55553. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55554. this._vertexBuffers["size"] = size;
  55555. dataOffset += 2;
  55556. if (this._isAnimationSheetEnabled) {
  55557. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55558. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55559. dataOffset += 1;
  55560. }
  55561. if (!this._isBillboardBased) {
  55562. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55563. this._vertexBuffers["direction"] = directionBuffer;
  55564. dataOffset += 3;
  55565. }
  55566. var offsets;
  55567. if (this._useInstancing) {
  55568. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55569. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55570. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55571. }
  55572. else {
  55573. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55574. dataOffset += 2;
  55575. }
  55576. this._vertexBuffers["offset"] = offsets;
  55577. };
  55578. ParticleSystem.prototype._createIndexBuffer = function () {
  55579. if (this._useInstancing) {
  55580. return;
  55581. }
  55582. var indices = [];
  55583. var index = 0;
  55584. for (var count = 0; count < this._capacity; count++) {
  55585. indices.push(index);
  55586. indices.push(index + 1);
  55587. indices.push(index + 2);
  55588. indices.push(index);
  55589. indices.push(index + 2);
  55590. indices.push(index + 3);
  55591. index += 4;
  55592. }
  55593. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55594. };
  55595. /**
  55596. * Gets the maximum number of particles active at the same time.
  55597. * @returns The max number of active particles.
  55598. */
  55599. ParticleSystem.prototype.getCapacity = function () {
  55600. return this._capacity;
  55601. };
  55602. /**
  55603. * Gets Wether there are still active particles in the system.
  55604. * @returns True if it is alive, otherwise false.
  55605. */
  55606. ParticleSystem.prototype.isAlive = function () {
  55607. return this._alive;
  55608. };
  55609. /**
  55610. * Gets Wether the system has been started.
  55611. * @returns True if it has been started, otherwise false.
  55612. */
  55613. ParticleSystem.prototype.isStarted = function () {
  55614. return this._started;
  55615. };
  55616. /**
  55617. * Starts the particle system and begins to emit.
  55618. */
  55619. ParticleSystem.prototype.start = function () {
  55620. this._started = true;
  55621. this._stopped = false;
  55622. this._actualFrame = 0;
  55623. if (this.subEmitters && this.subEmitters.length != 0) {
  55624. this.activeSubSystems = new Array();
  55625. }
  55626. if (this.preWarmCycles) {
  55627. for (var index = 0; index < this.preWarmCycles; index++) {
  55628. this.animate(true);
  55629. }
  55630. }
  55631. };
  55632. /**
  55633. * Stops the particle system.
  55634. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  55635. */
  55636. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55637. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55638. this._stopped = true;
  55639. if (stopSubEmitters) {
  55640. this._stopSubEmitters();
  55641. }
  55642. };
  55643. // animation sheet
  55644. /**
  55645. * Remove all active particles
  55646. */
  55647. ParticleSystem.prototype.reset = function () {
  55648. this._stockParticles = [];
  55649. this._particles = [];
  55650. };
  55651. /**
  55652. * @hidden (for internal use only)
  55653. */
  55654. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55655. var offset = index * this._vertexBufferSize;
  55656. this._vertexData[offset++] = particle.position.x;
  55657. this._vertexData[offset++] = particle.position.y;
  55658. this._vertexData[offset++] = particle.position.z;
  55659. this._vertexData[offset++] = particle.color.r;
  55660. this._vertexData[offset++] = particle.color.g;
  55661. this._vertexData[offset++] = particle.color.b;
  55662. this._vertexData[offset++] = particle.color.a;
  55663. this._vertexData[offset++] = particle.angle;
  55664. this._vertexData[offset++] = particle.scale.x * particle.size;
  55665. this._vertexData[offset++] = particle.scale.y * particle.size;
  55666. if (this._isAnimationSheetEnabled) {
  55667. this._vertexData[offset++] = particle.cellIndex;
  55668. }
  55669. if (!this._isBillboardBased) {
  55670. if (particle._initialDirection) {
  55671. this._vertexData[offset++] = particle._initialDirection.x;
  55672. this._vertexData[offset++] = particle._initialDirection.y;
  55673. this._vertexData[offset++] = particle._initialDirection.z;
  55674. }
  55675. else {
  55676. this._vertexData[offset++] = particle.direction.x;
  55677. this._vertexData[offset++] = particle.direction.y;
  55678. this._vertexData[offset++] = particle.direction.z;
  55679. }
  55680. }
  55681. if (!this._useInstancing) {
  55682. if (this._isAnimationSheetEnabled) {
  55683. if (offsetX === 0)
  55684. offsetX = this._epsilon;
  55685. else if (offsetX === 1)
  55686. offsetX = 1 - this._epsilon;
  55687. if (offsetY === 0)
  55688. offsetY = this._epsilon;
  55689. else if (offsetY === 1)
  55690. offsetY = 1 - this._epsilon;
  55691. }
  55692. this._vertexData[offset++] = offsetX;
  55693. this._vertexData[offset++] = offsetY;
  55694. }
  55695. };
  55696. ParticleSystem.prototype._stopSubEmitters = function () {
  55697. if (!this.activeSubSystems) {
  55698. return;
  55699. }
  55700. this.activeSubSystems.forEach(function (subSystem) {
  55701. subSystem.stop(true);
  55702. });
  55703. this.activeSubSystems = new Array();
  55704. };
  55705. ParticleSystem.prototype._removeFromRoot = function () {
  55706. if (!this._rootParticleSystem) {
  55707. return;
  55708. }
  55709. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55710. if (index !== -1) {
  55711. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55712. }
  55713. };
  55714. // End of sub system methods
  55715. ParticleSystem.prototype._update = function (newParticles) {
  55716. // Update current
  55717. this._alive = this._particles.length > 0;
  55718. this.updateFunction(this._particles);
  55719. // Add new ones
  55720. var worldMatrix;
  55721. if (this.emitter.position) {
  55722. var emitterMesh = this.emitter;
  55723. worldMatrix = emitterMesh.getWorldMatrix();
  55724. }
  55725. else {
  55726. var emitterPosition = this.emitter;
  55727. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55728. }
  55729. var particle;
  55730. var _loop_1 = function () {
  55731. if (this_1._particles.length === this_1._capacity) {
  55732. return "break";
  55733. }
  55734. particle = this_1._createParticle();
  55735. this_1._particles.push(particle);
  55736. // Emitter
  55737. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55738. if (this_1.startPositionFunction) {
  55739. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55740. }
  55741. else {
  55742. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55743. }
  55744. if (this_1.startDirectionFunction) {
  55745. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55746. }
  55747. else {
  55748. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55749. }
  55750. if (emitPower === 0) {
  55751. if (!particle._initialDirection) {
  55752. particle._initialDirection = particle.direction.clone();
  55753. }
  55754. else {
  55755. particle._initialDirection.copyFrom(particle.direction);
  55756. }
  55757. }
  55758. else {
  55759. particle._initialDirection = null;
  55760. }
  55761. particle.direction.scaleInPlace(emitPower);
  55762. // Life time
  55763. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55764. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55765. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55766. var factorGradient1 = currentGradient;
  55767. var factorGradient2 = nextGradient;
  55768. var lifeTime1 = factorGradient1.getFactor();
  55769. var lifeTime2 = factorGradient2.getFactor();
  55770. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55771. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55772. });
  55773. }
  55774. else {
  55775. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55776. }
  55777. // Size
  55778. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55779. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55780. }
  55781. else {
  55782. particle._currentSizeGradient = this_1._sizeGradients[0];
  55783. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55784. particle.size = particle._currentSize1;
  55785. if (this_1._sizeGradients.length > 1) {
  55786. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55787. }
  55788. else {
  55789. particle._currentSize2 = particle._currentSize1;
  55790. }
  55791. }
  55792. // Size and scale
  55793. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55794. // Angle
  55795. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55796. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55797. // Color
  55798. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55799. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55800. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55801. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55802. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55803. }
  55804. else {
  55805. particle._currentColorGradient = this_1._colorGradients[0];
  55806. particle._currentColorGradient.getColorToRef(particle.color);
  55807. particle._currentColor1.copyFrom(particle.color);
  55808. if (this_1._colorGradients.length > 1) {
  55809. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55810. }
  55811. else {
  55812. particle._currentColor2.copyFrom(particle.color);
  55813. }
  55814. }
  55815. // Sheet
  55816. if (this_1._isAnimationSheetEnabled) {
  55817. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55818. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55819. }
  55820. };
  55821. var this_1 = this, step;
  55822. for (var index = 0; index < newParticles; index++) {
  55823. var state_1 = _loop_1();
  55824. if (state_1 === "break")
  55825. break;
  55826. }
  55827. };
  55828. /** @hidden */
  55829. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55830. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55831. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55832. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55833. if (isAnimationSheetEnabled) {
  55834. attributeNamesOrOptions.push("cellIndex");
  55835. }
  55836. if (!isBillboardBased) {
  55837. attributeNamesOrOptions.push("direction");
  55838. }
  55839. return attributeNamesOrOptions;
  55840. };
  55841. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55842. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55843. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55844. if (isAnimationSheetEnabled) {
  55845. effectCreationOption.push("particlesInfos");
  55846. }
  55847. return effectCreationOption;
  55848. };
  55849. ParticleSystem.prototype._getEffect = function () {
  55850. if (this._customEffect) {
  55851. return this._customEffect;
  55852. }
  55853. ;
  55854. var defines = [];
  55855. if (this._scene.clipPlane) {
  55856. defines.push("#define CLIPPLANE");
  55857. }
  55858. if (this._isAnimationSheetEnabled) {
  55859. defines.push("#define ANIMATESHEET");
  55860. }
  55861. if (this._isBillboardBased) {
  55862. defines.push("#define BILLBOARD");
  55863. switch (this.billboardMode) {
  55864. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55865. defines.push("#define BILLBOARDY");
  55866. break;
  55867. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55868. default:
  55869. break;
  55870. }
  55871. }
  55872. // Effect
  55873. var join = defines.join("\n");
  55874. if (this._cachedDefines !== join) {
  55875. this._cachedDefines = join;
  55876. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55877. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55878. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55879. }
  55880. return this._effect;
  55881. };
  55882. /**
  55883. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55884. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55885. */
  55886. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55887. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55888. if (!this._started)
  55889. return;
  55890. if (!preWarmOnly) {
  55891. var effect = this._getEffect();
  55892. // Check
  55893. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55894. return;
  55895. if (this._currentRenderId === this._scene.getRenderId()) {
  55896. return;
  55897. }
  55898. this._currentRenderId = this._scene.getRenderId();
  55899. }
  55900. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55901. // determine the number of particles we need to create
  55902. var newParticles;
  55903. if (this.manualEmitCount > -1) {
  55904. newParticles = this.manualEmitCount;
  55905. this._newPartsExcess = 0;
  55906. this.manualEmitCount = 0;
  55907. }
  55908. else {
  55909. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55910. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55911. }
  55912. if (this._newPartsExcess > 1.0) {
  55913. newParticles += this._newPartsExcess >> 0;
  55914. this._newPartsExcess -= this._newPartsExcess >> 0;
  55915. }
  55916. this._alive = false;
  55917. if (!this._stopped) {
  55918. this._actualFrame += this._scaledUpdateSpeed;
  55919. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55920. this.stop();
  55921. }
  55922. else {
  55923. newParticles = 0;
  55924. }
  55925. this._update(newParticles);
  55926. // Stopped?
  55927. if (this._stopped) {
  55928. if (!this._alive) {
  55929. this._started = false;
  55930. if (this.onAnimationEnd) {
  55931. this.onAnimationEnd();
  55932. }
  55933. if (this.disposeOnStop) {
  55934. this._scene._toBeDisposed.push(this);
  55935. }
  55936. }
  55937. }
  55938. if (!preWarmOnly) {
  55939. // Update VBO
  55940. var offset = 0;
  55941. for (var index = 0; index < this._particles.length; index++) {
  55942. var particle = this._particles[index];
  55943. this._appendParticleVertices(offset, particle);
  55944. offset += this._useInstancing ? 1 : 4;
  55945. }
  55946. if (this._vertexBuffer) {
  55947. this._vertexBuffer.update(this._vertexData);
  55948. }
  55949. }
  55950. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55951. this.stop();
  55952. }
  55953. };
  55954. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55955. this._appendParticleVertex(offset++, particle, 0, 0);
  55956. if (!this._useInstancing) {
  55957. this._appendParticleVertex(offset++, particle, 1, 0);
  55958. this._appendParticleVertex(offset++, particle, 1, 1);
  55959. this._appendParticleVertex(offset++, particle, 0, 1);
  55960. }
  55961. };
  55962. /**
  55963. * Rebuilds the particle system.
  55964. */
  55965. ParticleSystem.prototype.rebuild = function () {
  55966. this._createIndexBuffer();
  55967. if (this._vertexBuffer) {
  55968. this._vertexBuffer._rebuild();
  55969. }
  55970. };
  55971. /**
  55972. * Is this system ready to be used/rendered
  55973. * @return true if the system is ready
  55974. */
  55975. ParticleSystem.prototype.isReady = function () {
  55976. var effect = this._getEffect();
  55977. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55978. return false;
  55979. }
  55980. return true;
  55981. };
  55982. /**
  55983. * Renders the particle system in its current state.
  55984. * @returns the current number of particles
  55985. */
  55986. ParticleSystem.prototype.render = function () {
  55987. var effect = this._getEffect();
  55988. // Check
  55989. if (!this.isReady() || !this._particles.length) {
  55990. return 0;
  55991. }
  55992. var engine = this._scene.getEngine();
  55993. // Render
  55994. engine.enableEffect(effect);
  55995. engine.setState(false);
  55996. var viewMatrix = this._scene.getViewMatrix();
  55997. effect.setTexture("diffuseSampler", this.particleTexture);
  55998. effect.setMatrix("view", viewMatrix);
  55999. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56000. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56001. var baseSize = this.particleTexture.getBaseSize();
  56002. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56003. }
  56004. effect.setVector2("translationPivot", this.translationPivot);
  56005. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56006. if (this._isBillboardBased) {
  56007. var camera = this._scene.activeCamera;
  56008. effect.setVector3("eyePosition", camera.globalPosition);
  56009. }
  56010. if (this._scene.clipPlane) {
  56011. var clipPlane = this._scene.clipPlane;
  56012. var invView = viewMatrix.clone();
  56013. invView.invert();
  56014. effect.setMatrix("invView", invView);
  56015. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56016. }
  56017. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56018. // Draw order
  56019. switch (this.blendMode) {
  56020. case ParticleSystem.BLENDMODE_ADD:
  56021. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56022. break;
  56023. case ParticleSystem.BLENDMODE_ONEONE:
  56024. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56025. break;
  56026. case ParticleSystem.BLENDMODE_STANDARD:
  56027. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56028. break;
  56029. }
  56030. if (this.forceDepthWrite) {
  56031. engine.setDepthWrite(true);
  56032. }
  56033. if (this._useInstancing) {
  56034. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56035. engine.unbindInstanceAttributes();
  56036. }
  56037. else {
  56038. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56039. }
  56040. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56041. return this._particles.length;
  56042. };
  56043. /**
  56044. * Disposes the particle system and free the associated resources
  56045. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56046. */
  56047. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56048. if (disposeTexture === void 0) { disposeTexture = true; }
  56049. if (this._vertexBuffer) {
  56050. this._vertexBuffer.dispose();
  56051. this._vertexBuffer = null;
  56052. }
  56053. if (this._spriteBuffer) {
  56054. this._spriteBuffer.dispose();
  56055. this._spriteBuffer = null;
  56056. }
  56057. if (this._indexBuffer) {
  56058. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56059. this._indexBuffer = null;
  56060. }
  56061. if (disposeTexture && this.particleTexture) {
  56062. this.particleTexture.dispose();
  56063. this.particleTexture = null;
  56064. }
  56065. this._removeFromRoot();
  56066. // Remove from scene
  56067. var index = this._scene.particleSystems.indexOf(this);
  56068. if (index > -1) {
  56069. this._scene.particleSystems.splice(index, 1);
  56070. }
  56071. // Callback
  56072. this.onDisposeObservable.notifyObservers(this);
  56073. this.onDisposeObservable.clear();
  56074. };
  56075. /**
  56076. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56077. * @param radius The radius of the sphere to emit from
  56078. * @returns the emitter
  56079. */
  56080. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56081. if (radius === void 0) { radius = 1; }
  56082. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56083. this.particleEmitterType = particleEmitter;
  56084. return particleEmitter;
  56085. };
  56086. /**
  56087. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56088. * @param radius The radius of the sphere to emit from
  56089. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56090. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56091. * @returns the emitter
  56092. */
  56093. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56094. if (radius === void 0) { radius = 1; }
  56095. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56096. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56097. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56098. this.particleEmitterType = particleEmitter;
  56099. return particleEmitter;
  56100. };
  56101. /**
  56102. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56103. * @param radius The radius of the cone to emit from
  56104. * @param angle The base angle of the cone
  56105. * @returns the emitter
  56106. */
  56107. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56108. if (radius === void 0) { radius = 1; }
  56109. if (angle === void 0) { angle = Math.PI / 4; }
  56110. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56111. this.particleEmitterType = particleEmitter;
  56112. return particleEmitter;
  56113. };
  56114. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  56115. /**
  56116. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56117. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56118. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56119. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56120. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56121. * @returns the emitter
  56122. */
  56123. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56124. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56125. this.particleEmitterType = particleEmitter;
  56126. this.direction1 = direction1;
  56127. this.direction2 = direction2;
  56128. this.minEmitBox = minEmitBox;
  56129. this.maxEmitBox = maxEmitBox;
  56130. return particleEmitter;
  56131. };
  56132. // Clone
  56133. /**
  56134. * Clones the particle system.
  56135. * @param name The name of the cloned object
  56136. * @param newEmitter The new emitter to use
  56137. * @returns the cloned particle system
  56138. */
  56139. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56140. var custom = null;
  56141. var program = null;
  56142. if (this.customShader != null) {
  56143. program = this.customShader;
  56144. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56145. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56146. }
  56147. else if (this._customEffect) {
  56148. custom = this._customEffect;
  56149. }
  56150. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56151. result.customShader = program;
  56152. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56153. if (newEmitter === undefined) {
  56154. newEmitter = this.emitter;
  56155. }
  56156. result.emitter = newEmitter;
  56157. if (this.particleTexture) {
  56158. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56159. }
  56160. if (!this.preventAutoStart) {
  56161. result.start();
  56162. }
  56163. return result;
  56164. };
  56165. /**
  56166. * Serializes the particle system to a JSON object.
  56167. * @returns the JSON object
  56168. */
  56169. ParticleSystem.prototype.serialize = function () {
  56170. var serializationObject = {};
  56171. ParticleSystem._Serialize(serializationObject, this);
  56172. serializationObject.textureMask = this.textureMask.asArray();
  56173. serializationObject.customShader = this.customShader;
  56174. serializationObject.preventAutoStart = this.preventAutoStart;
  56175. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56176. return serializationObject;
  56177. };
  56178. /** @hidden */
  56179. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56180. serializationObject.name = particleSystem.name;
  56181. serializationObject.id = particleSystem.id;
  56182. serializationObject.capacity = particleSystem.getCapacity();
  56183. // Emitter
  56184. if (particleSystem.emitter.position) {
  56185. var emitterMesh = particleSystem.emitter;
  56186. serializationObject.emitterId = emitterMesh.id;
  56187. }
  56188. else {
  56189. var emitterPosition = particleSystem.emitter;
  56190. serializationObject.emitter = emitterPosition.asArray();
  56191. }
  56192. // Emitter
  56193. if (particleSystem.particleEmitterType) {
  56194. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56195. }
  56196. if (particleSystem.particleTexture) {
  56197. serializationObject.textureName = particleSystem.particleTexture.name;
  56198. }
  56199. // Animations
  56200. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56201. // Particle system
  56202. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56203. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56204. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56205. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56206. serializationObject.minSize = particleSystem.minSize;
  56207. serializationObject.maxSize = particleSystem.maxSize;
  56208. serializationObject.minScaleX = particleSystem.minScaleX;
  56209. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56210. serializationObject.minScaleY = particleSystem.minScaleY;
  56211. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56212. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56213. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56214. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56215. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56216. serializationObject.emitRate = particleSystem.emitRate;
  56217. serializationObject.gravity = particleSystem.gravity.asArray();
  56218. serializationObject.color1 = particleSystem.color1.asArray();
  56219. serializationObject.color2 = particleSystem.color2.asArray();
  56220. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56221. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56222. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56223. serializationObject.blendMode = particleSystem.blendMode;
  56224. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56225. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56226. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56227. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56228. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56229. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56230. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56231. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56232. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56233. var colorGradients = particleSystem.getColorGradients();
  56234. if (colorGradients) {
  56235. serializationObject.colorGradients = [];
  56236. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56237. var colorGradient = colorGradients_1[_i];
  56238. var serializedGradient = {
  56239. gradient: colorGradient.gradient,
  56240. color1: colorGradient.color1.asArray()
  56241. };
  56242. if (colorGradient.color2) {
  56243. serializedGradient.color2 = colorGradient.color2.asArray();
  56244. }
  56245. serializationObject.colorGradients.push(serializedGradient);
  56246. }
  56247. }
  56248. var sizeGradients = particleSystem.getSizeGradients();
  56249. if (sizeGradients) {
  56250. serializationObject.sizeGradients = [];
  56251. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56252. var sizeGradient = sizeGradients_1[_a];
  56253. var serializedGradient = {
  56254. gradient: sizeGradient.gradient,
  56255. factor1: sizeGradient.factor1
  56256. };
  56257. if (sizeGradient.factor2 !== undefined) {
  56258. serializedGradient.factor2 = sizeGradient.factor2;
  56259. }
  56260. serializationObject.sizeGradients.push(serializedGradient);
  56261. }
  56262. }
  56263. };
  56264. /** @hidden */
  56265. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56266. // Texture
  56267. if (parsedParticleSystem.textureName) {
  56268. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56269. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56270. }
  56271. // Emitter
  56272. if (parsedParticleSystem.emitterId === undefined) {
  56273. particleSystem.emitter = BABYLON.Vector3.Zero();
  56274. }
  56275. else if (parsedParticleSystem.emitterId) {
  56276. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56277. }
  56278. else {
  56279. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56280. }
  56281. // Misc.
  56282. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56283. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56284. }
  56285. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56286. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56287. }
  56288. // Animations
  56289. if (parsedParticleSystem.animations) {
  56290. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56291. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56292. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56293. }
  56294. }
  56295. if (parsedParticleSystem.autoAnimate) {
  56296. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56297. }
  56298. // Particle system
  56299. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56300. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56301. particleSystem.minSize = parsedParticleSystem.minSize;
  56302. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56303. if (parsedParticleSystem.minScaleX) {
  56304. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56305. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56306. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56307. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56308. }
  56309. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56310. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56311. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56312. }
  56313. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56314. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56315. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56316. }
  56317. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56318. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56319. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56320. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56321. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56322. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56323. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56324. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56325. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56326. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56327. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56328. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56329. if (parsedParticleSystem.colorGradients) {
  56330. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56331. var colorGradient = _a[_i];
  56332. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56333. }
  56334. }
  56335. if (parsedParticleSystem.sizeGradients) {
  56336. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56337. var sizeGradient = _c[_b];
  56338. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56339. }
  56340. }
  56341. // Emitter
  56342. var emitterType;
  56343. if (parsedParticleSystem.particleEmitterType) {
  56344. switch (parsedParticleSystem.particleEmitterType.type) {
  56345. case "SphereParticleEmitter":
  56346. emitterType = new BABYLON.SphereParticleEmitter();
  56347. break;
  56348. case "SphereDirectedParticleEmitter":
  56349. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56350. break;
  56351. case "ConeEmitter":
  56352. case "ConeParticleEmitter":
  56353. emitterType = new BABYLON.ConeParticleEmitter();
  56354. break;
  56355. case "BoxEmitter":
  56356. case "BoxParticleEmitter":
  56357. default:
  56358. emitterType = new BABYLON.BoxParticleEmitter();
  56359. break;
  56360. }
  56361. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56362. }
  56363. else {
  56364. emitterType = new BABYLON.BoxParticleEmitter();
  56365. emitterType.parse(parsedParticleSystem);
  56366. }
  56367. particleSystem.particleEmitterType = emitterType;
  56368. // Animation sheet
  56369. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56370. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56371. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56372. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56373. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56374. };
  56375. /**
  56376. * Parses a JSON object to create a particle system.
  56377. * @param parsedParticleSystem The JSON object to parse
  56378. * @param scene The scene to create the particle system in
  56379. * @param rootUrl The root url to use to load external dependencies like texture
  56380. * @returns the Parsed particle system
  56381. */
  56382. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56383. var name = parsedParticleSystem.name;
  56384. var custom = null;
  56385. var program = null;
  56386. if (parsedParticleSystem.customShader) {
  56387. program = parsedParticleSystem.customShader;
  56388. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56389. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56390. }
  56391. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56392. particleSystem.customShader = program;
  56393. if (parsedParticleSystem.id) {
  56394. particleSystem.id = parsedParticleSystem.id;
  56395. }
  56396. // Auto start
  56397. if (parsedParticleSystem.preventAutoStart) {
  56398. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56399. }
  56400. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56401. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56402. if (!particleSystem.preventAutoStart) {
  56403. particleSystem.start();
  56404. }
  56405. return particleSystem;
  56406. };
  56407. /**
  56408. * Source color is added to the destination color without alpha affecting the result.
  56409. */
  56410. ParticleSystem.BLENDMODE_ONEONE = 0;
  56411. /**
  56412. * Blend current color and particle color using particle’s alpha.
  56413. */
  56414. ParticleSystem.BLENDMODE_STANDARD = 1;
  56415. /**
  56416. * Add current color and particle color multiplied by particle’s alpha.
  56417. */
  56418. ParticleSystem.BLENDMODE_ADD = 2;
  56419. return ParticleSystem;
  56420. }());
  56421. BABYLON.ParticleSystem = ParticleSystem;
  56422. })(BABYLON || (BABYLON = {}));
  56423. //# sourceMappingURL=babylon.particleSystem.js.map
  56424. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56425. var BABYLON;
  56426. (function (BABYLON) {
  56427. /**
  56428. * Particle emitter emitting particles from the inside of a box.
  56429. * It emits the particles randomly between 2 given directions.
  56430. */
  56431. var BoxParticleEmitter = /** @class */ (function () {
  56432. /**
  56433. * Creates a new instance BoxParticleEmitter
  56434. */
  56435. function BoxParticleEmitter() {
  56436. /**
  56437. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56438. */
  56439. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56440. /**
  56441. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56442. */
  56443. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56444. /**
  56445. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56446. */
  56447. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56448. /**
  56449. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56450. */
  56451. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56452. }
  56453. /**
  56454. * Called by the particle System when the direction is computed for the created particle.
  56455. * @param worldMatrix is the world matrix of the particle system
  56456. * @param directionToUpdate is the direction vector to update with the result
  56457. * @param particle is the particle we are computed the direction for
  56458. */
  56459. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56460. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56461. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56462. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56463. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56464. };
  56465. /**
  56466. * Called by the particle System when the position is computed for the created particle.
  56467. * @param worldMatrix is the world matrix of the particle system
  56468. * @param positionToUpdate is the position vector to update with the result
  56469. * @param particle is the particle we are computed the position for
  56470. */
  56471. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56472. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56473. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56474. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56475. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56476. };
  56477. /**
  56478. * Clones the current emitter and returns a copy of it
  56479. * @returns the new emitter
  56480. */
  56481. BoxParticleEmitter.prototype.clone = function () {
  56482. var newOne = new BoxParticleEmitter();
  56483. BABYLON.Tools.DeepCopy(this, newOne);
  56484. return newOne;
  56485. };
  56486. /**
  56487. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56488. * @param effect defines the update shader
  56489. */
  56490. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56491. effect.setVector3("direction1", this.direction1);
  56492. effect.setVector3("direction2", this.direction2);
  56493. effect.setVector3("minEmitBox", this.minEmitBox);
  56494. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56495. };
  56496. /**
  56497. * Returns a string to use to update the GPU particles update shader
  56498. * @returns a string containng the defines string
  56499. */
  56500. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56501. return "#define BOXEMITTER";
  56502. };
  56503. /**
  56504. * Returns the string "BoxParticleEmitter"
  56505. * @returns a string containing the class name
  56506. */
  56507. BoxParticleEmitter.prototype.getClassName = function () {
  56508. return "BoxParticleEmitter";
  56509. };
  56510. /**
  56511. * Serializes the particle system to a JSON object.
  56512. * @returns the JSON object
  56513. */
  56514. BoxParticleEmitter.prototype.serialize = function () {
  56515. var serializationObject = {};
  56516. serializationObject.type = this.getClassName();
  56517. serializationObject.direction1 = this.direction1.asArray();
  56518. serializationObject.direction2 = this.direction2.asArray();
  56519. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56520. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56521. return serializationObject;
  56522. };
  56523. /**
  56524. * Parse properties from a JSON object
  56525. * @param serializationObject defines the JSON object
  56526. */
  56527. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56528. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56529. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56530. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56531. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56532. };
  56533. return BoxParticleEmitter;
  56534. }());
  56535. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56536. })(BABYLON || (BABYLON = {}));
  56537. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56538. var BABYLON;
  56539. (function (BABYLON) {
  56540. /**
  56541. * Particle emitter emitting particles from the inside of a cone.
  56542. * It emits the particles alongside the cone volume from the base to the particle.
  56543. * The emission direction might be randomized.
  56544. */
  56545. var ConeParticleEmitter = /** @class */ (function () {
  56546. /**
  56547. * Creates a new instance ConeParticleEmitter
  56548. * @param radius the radius of the emission cone (1 by default)
  56549. * @param angles the cone base angle (PI by default)
  56550. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56551. */
  56552. function ConeParticleEmitter(radius, angle,
  56553. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56554. directionRandomizer) {
  56555. if (radius === void 0) { radius = 1; }
  56556. if (angle === void 0) { angle = Math.PI; }
  56557. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56558. this.directionRandomizer = directionRandomizer;
  56559. /**
  56560. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56561. */
  56562. this.radiusRange = 1;
  56563. /**
  56564. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56565. */
  56566. this.heightRange = 1;
  56567. this.angle = angle;
  56568. this.radius = radius;
  56569. }
  56570. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56571. /**
  56572. * Gets or sets the radius of the emission cone
  56573. */
  56574. get: function () {
  56575. return this._radius;
  56576. },
  56577. set: function (value) {
  56578. this._radius = value;
  56579. this._buildHeight();
  56580. },
  56581. enumerable: true,
  56582. configurable: true
  56583. });
  56584. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56585. /**
  56586. * Gets or sets the angle of the emission cone
  56587. */
  56588. get: function () {
  56589. return this._angle;
  56590. },
  56591. set: function (value) {
  56592. this._angle = value;
  56593. this._buildHeight();
  56594. },
  56595. enumerable: true,
  56596. configurable: true
  56597. });
  56598. ConeParticleEmitter.prototype._buildHeight = function () {
  56599. if (this._angle !== 0) {
  56600. this._height = this._radius / Math.tan(this._angle / 2);
  56601. }
  56602. else {
  56603. this._height = 1;
  56604. }
  56605. };
  56606. /**
  56607. * Called by the particle System when the direction is computed for the created particle.
  56608. * @param worldMatrix is the world matrix of the particle system
  56609. * @param directionToUpdate is the direction vector to update with the result
  56610. * @param particle is the particle we are computed the direction for
  56611. */
  56612. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56613. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56614. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56615. }
  56616. else {
  56617. // measure the direction Vector from the emitter to the particle.
  56618. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56619. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56620. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56621. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56622. direction.x += randX;
  56623. direction.y += randY;
  56624. direction.z += randZ;
  56625. direction.normalize();
  56626. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56627. }
  56628. };
  56629. /**
  56630. * Called by the particle System when the position is computed for the created particle.
  56631. * @param worldMatrix is the world matrix of the particle system
  56632. * @param positionToUpdate is the position vector to update with the result
  56633. * @param particle is the particle we are computed the position for
  56634. */
  56635. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56636. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56637. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56638. // Better distribution in a cone at normal angles.
  56639. h = 1 - h * h;
  56640. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56641. radius = radius * h;
  56642. var randX = radius * Math.sin(s);
  56643. var randZ = radius * Math.cos(s);
  56644. var randY = h * this._height;
  56645. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56646. };
  56647. /**
  56648. * Clones the current emitter and returns a copy of it
  56649. * @returns the new emitter
  56650. */
  56651. ConeParticleEmitter.prototype.clone = function () {
  56652. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56653. BABYLON.Tools.DeepCopy(this, newOne);
  56654. return newOne;
  56655. };
  56656. /**
  56657. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56658. * @param effect defines the update shader
  56659. */
  56660. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56661. effect.setFloat2("radius", this._radius, this.radiusRange);
  56662. effect.setFloat("coneAngle", this._angle);
  56663. effect.setFloat2("height", this._height, this.heightRange);
  56664. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56665. };
  56666. /**
  56667. * Returns a string to use to update the GPU particles update shader
  56668. * @returns a string containng the defines string
  56669. */
  56670. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56671. return "#define CONEEMITTER";
  56672. };
  56673. /**
  56674. * Returns the string "ConeParticleEmitter"
  56675. * @returns a string containing the class name
  56676. */
  56677. ConeParticleEmitter.prototype.getClassName = function () {
  56678. return "ConeParticleEmitter";
  56679. };
  56680. /**
  56681. * Serializes the particle system to a JSON object.
  56682. * @returns the JSON object
  56683. */
  56684. ConeParticleEmitter.prototype.serialize = function () {
  56685. var serializationObject = {};
  56686. serializationObject.type = this.getClassName();
  56687. serializationObject.radius = this._radius;
  56688. serializationObject.angle = this._angle;
  56689. serializationObject.directionRandomizer = this.directionRandomizer;
  56690. return serializationObject;
  56691. };
  56692. /**
  56693. * Parse properties from a JSON object
  56694. * @param serializationObject defines the JSON object
  56695. */
  56696. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56697. this.radius = serializationObject.radius;
  56698. this.angle = serializationObject.angle;
  56699. this.directionRandomizer = serializationObject.directionRandomizer;
  56700. };
  56701. return ConeParticleEmitter;
  56702. }());
  56703. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56704. })(BABYLON || (BABYLON = {}));
  56705. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56706. var BABYLON;
  56707. (function (BABYLON) {
  56708. /**
  56709. * Particle emitter emitting particles from the inside of a sphere.
  56710. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56711. */
  56712. var SphereParticleEmitter = /** @class */ (function () {
  56713. /**
  56714. * Creates a new instance SphereParticleEmitter
  56715. * @param radius the radius of the emission sphere (1 by default)
  56716. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56717. */
  56718. function SphereParticleEmitter(
  56719. /**
  56720. * The radius of the emission sphere.
  56721. */
  56722. radius,
  56723. /**
  56724. * How much to randomize the particle direction [0-1].
  56725. */
  56726. directionRandomizer) {
  56727. if (radius === void 0) { radius = 1; }
  56728. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56729. this.radius = radius;
  56730. this.directionRandomizer = directionRandomizer;
  56731. /**
  56732. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56733. */
  56734. this.radiusRange = 1;
  56735. }
  56736. /**
  56737. * Called by the particle System when the direction is computed for the created particle.
  56738. * @param worldMatrix is the world matrix of the particle system
  56739. * @param directionToUpdate is the direction vector to update with the result
  56740. * @param particle is the particle we are computed the direction for
  56741. */
  56742. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56743. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56744. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56745. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56746. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56747. direction.x += randX;
  56748. direction.y += randY;
  56749. direction.z += randZ;
  56750. direction.normalize();
  56751. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56752. };
  56753. /**
  56754. * Called by the particle System when the position is computed for the created particle.
  56755. * @param worldMatrix is the world matrix of the particle system
  56756. * @param positionToUpdate is the position vector to update with the result
  56757. * @param particle is the particle we are computed the position for
  56758. */
  56759. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56760. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56761. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56762. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56763. var theta = Math.acos(2 * v - 1);
  56764. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56765. var randY = randRadius * Math.cos(theta);
  56766. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56767. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56768. };
  56769. /**
  56770. * Clones the current emitter and returns a copy of it
  56771. * @returns the new emitter
  56772. */
  56773. SphereParticleEmitter.prototype.clone = function () {
  56774. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56775. BABYLON.Tools.DeepCopy(this, newOne);
  56776. return newOne;
  56777. };
  56778. /**
  56779. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56780. * @param effect defines the update shader
  56781. */
  56782. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56783. effect.setFloat("radius", this.radius);
  56784. effect.setFloat("radiusRange", this.radiusRange);
  56785. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56786. };
  56787. /**
  56788. * Returns a string to use to update the GPU particles update shader
  56789. * @returns a string containng the defines string
  56790. */
  56791. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56792. return "#define SPHEREEMITTER";
  56793. };
  56794. /**
  56795. * Returns the string "SphereParticleEmitter"
  56796. * @returns a string containing the class name
  56797. */
  56798. SphereParticleEmitter.prototype.getClassName = function () {
  56799. return "SphereParticleEmitter";
  56800. };
  56801. /**
  56802. * Serializes the particle system to a JSON object.
  56803. * @returns the JSON object
  56804. */
  56805. SphereParticleEmitter.prototype.serialize = function () {
  56806. var serializationObject = {};
  56807. serializationObject.type = this.getClassName();
  56808. serializationObject.radius = this.radius;
  56809. serializationObject.radiusRange = this.radiusRange;
  56810. serializationObject.directionRandomizer = this.directionRandomizer;
  56811. return serializationObject;
  56812. };
  56813. /**
  56814. * Parse properties from a JSON object
  56815. * @param serializationObject defines the JSON object
  56816. */
  56817. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56818. this.radius = serializationObject.radius;
  56819. this.radiusRange = serializationObject.radiusRange;
  56820. this.directionRandomizer = serializationObject.directionRandomizer;
  56821. };
  56822. return SphereParticleEmitter;
  56823. }());
  56824. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56825. /**
  56826. * Particle emitter emitting particles from the inside of a sphere.
  56827. * It emits the particles randomly between two vectors.
  56828. */
  56829. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56830. __extends(SphereDirectedParticleEmitter, _super);
  56831. /**
  56832. * Creates a new instance SphereDirectedParticleEmitter
  56833. * @param radius the radius of the emission sphere (1 by default)
  56834. * @param direction1 the min limit of the emission direction (up vector by default)
  56835. * @param direction2 the max limit of the emission direction (up vector by default)
  56836. */
  56837. function SphereDirectedParticleEmitter(radius,
  56838. /**
  56839. * The min limit of the emission direction.
  56840. */
  56841. direction1,
  56842. /**
  56843. * The max limit of the emission direction.
  56844. */
  56845. direction2) {
  56846. if (radius === void 0) { radius = 1; }
  56847. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56848. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56849. var _this = _super.call(this, radius) || this;
  56850. _this.direction1 = direction1;
  56851. _this.direction2 = direction2;
  56852. return _this;
  56853. }
  56854. /**
  56855. * Called by the particle System when the direction is computed for the created particle.
  56856. * @param worldMatrix is the world matrix of the particle system
  56857. * @param directionToUpdate is the direction vector to update with the result
  56858. * @param particle is the particle we are computed the direction for
  56859. */
  56860. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56861. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56862. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56863. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56864. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56865. };
  56866. /**
  56867. * Clones the current emitter and returns a copy of it
  56868. * @returns the new emitter
  56869. */
  56870. SphereDirectedParticleEmitter.prototype.clone = function () {
  56871. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56872. BABYLON.Tools.DeepCopy(this, newOne);
  56873. return newOne;
  56874. };
  56875. /**
  56876. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56877. * @param effect defines the update shader
  56878. */
  56879. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56880. effect.setFloat("radius", this.radius);
  56881. effect.setFloat("radiusRange", this.radiusRange);
  56882. effect.setVector3("direction1", this.direction1);
  56883. effect.setVector3("direction2", this.direction2);
  56884. };
  56885. /**
  56886. * Returns a string to use to update the GPU particles update shader
  56887. * @returns a string containng the defines string
  56888. */
  56889. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56890. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56891. };
  56892. /**
  56893. * Returns the string "SphereDirectedParticleEmitter"
  56894. * @returns a string containing the class name
  56895. */
  56896. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56897. return "SphereDirectedParticleEmitter";
  56898. };
  56899. /**
  56900. * Serializes the particle system to a JSON object.
  56901. * @returns the JSON object
  56902. */
  56903. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56904. var serializationObject = _super.prototype.serialize.call(this);
  56905. serializationObject.direction1 = this.direction1.asArray();
  56906. serializationObject.direction2 = this.direction2.asArray();
  56907. return serializationObject;
  56908. };
  56909. /**
  56910. * Parse properties from a JSON object
  56911. * @param serializationObject defines the JSON object
  56912. */
  56913. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56914. _super.prototype.parse.call(this, serializationObject);
  56915. this.direction1.copyFrom(serializationObject.direction1);
  56916. this.direction2.copyFrom(serializationObject.direction2);
  56917. };
  56918. return SphereDirectedParticleEmitter;
  56919. }(SphereParticleEmitter));
  56920. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56921. })(BABYLON || (BABYLON = {}));
  56922. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56923. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56924. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56925. s = arguments[i];
  56926. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56927. t[p] = s[p];
  56928. }
  56929. return t;
  56930. };
  56931. var BABYLON;
  56932. (function (BABYLON) {
  56933. /**
  56934. * This represents a GPU particle system in Babylon
  56935. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56936. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56937. */
  56938. var GPUParticleSystem = /** @class */ (function () {
  56939. /**
  56940. * Instantiates a GPU particle system.
  56941. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  56942. * @param name The name of the particle system
  56943. * @param options The options used to create the system
  56944. * @param scene The scene the particle system belongs to
  56945. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56946. */
  56947. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  56948. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56949. /**
  56950. * The emitter represents the Mesh or position we are attaching the particle system to.
  56951. */
  56952. this.emitter = null;
  56953. /**
  56954. * The rendering group used by the Particle system to chose when to render.
  56955. */
  56956. this.renderingGroupId = 0;
  56957. /**
  56958. * The layer mask we are rendering the particles through.
  56959. */
  56960. this.layerMask = 0x0FFFFFFF;
  56961. this._accumulatedCount = 0;
  56962. this._targetIndex = 0;
  56963. this._currentRenderId = -1;
  56964. this._started = false;
  56965. this._stopped = false;
  56966. this._timeDelta = 0;
  56967. this._attributesStrideSize = 21;
  56968. this._actualFrame = 0;
  56969. /**
  56970. * List of animations used by the particle system.
  56971. */
  56972. this.animations = [];
  56973. /**
  56974. * An event triggered when the system is disposed.
  56975. */
  56976. this.onDisposeObservable = new BABYLON.Observable();
  56977. /**
  56978. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56979. */
  56980. this.updateSpeed = 0.01;
  56981. /**
  56982. * The amount of time the particle system is running (depends of the overall update speed).
  56983. */
  56984. this.targetStopDuration = 0;
  56985. /**
  56986. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56987. */
  56988. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56989. /**
  56990. * Minimum life time of emitting particles.
  56991. */
  56992. this.minLifeTime = 1;
  56993. /**
  56994. * Maximum life time of emitting particles.
  56995. */
  56996. this.maxLifeTime = 1;
  56997. /**
  56998. * Minimum Size of emitting particles.
  56999. */
  57000. this.minSize = 1;
  57001. /**
  57002. * Maximum Size of emitting particles.
  57003. */
  57004. this.maxSize = 1;
  57005. /**
  57006. * Minimum scale of emitting particles on X axis.
  57007. */
  57008. this.minScaleX = 1;
  57009. /**
  57010. * Maximum scale of emitting particles on X axis.
  57011. */
  57012. this.maxScaleX = 1;
  57013. /**
  57014. * Minimum scale of emitting particles on Y axis.
  57015. */
  57016. this.minScaleY = 1;
  57017. /**
  57018. * Maximum scale of emitting particles on Y axis.
  57019. */
  57020. this.maxScaleY = 1;
  57021. /**
  57022. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57023. */
  57024. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57025. /**
  57026. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57027. */
  57028. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57029. /**
  57030. * Color the particle will have at the end of its lifetime.
  57031. */
  57032. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57033. /**
  57034. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57035. */
  57036. this.emitRate = 100;
  57037. /**
  57038. * You can use gravity if you want to give an orientation to your particles.
  57039. */
  57040. this.gravity = BABYLON.Vector3.Zero();
  57041. /**
  57042. * Minimum power of emitting particles.
  57043. */
  57044. this.minEmitPower = 1;
  57045. /**
  57046. * Maximum power of emitting particles.
  57047. */
  57048. this.maxEmitPower = 1;
  57049. /**
  57050. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57051. */
  57052. this.minAngularSpeed = 0;
  57053. /**
  57054. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57055. */
  57056. this.maxAngularSpeed = 0;
  57057. /**
  57058. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57059. * to override the particles.
  57060. */
  57061. this.forceDepthWrite = false;
  57062. this._preWarmDone = false;
  57063. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  57064. this.preWarmCycles = 0;
  57065. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57066. this.preWarmStepOffset = 1;
  57067. /**
  57068. * Gets or sets the minimal initial rotation in radians.
  57069. */
  57070. this.minInitialRotation = 0;
  57071. /**
  57072. * Gets or sets the maximal initial rotation in radians.
  57073. */
  57074. this.maxInitialRotation = 0;
  57075. /**
  57076. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  57077. */
  57078. this.spriteCellChangeSpeed = 1;
  57079. /**
  57080. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57081. */
  57082. this.startSpriteCellID = 0;
  57083. /**
  57084. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57085. */
  57086. this.endSpriteCellID = 0;
  57087. /**
  57088. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57089. */
  57090. this.spriteCellWidth = 0;
  57091. /**
  57092. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57093. */
  57094. this.spriteCellHeight = 0;
  57095. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57096. this.translationPivot = new BABYLON.Vector2(0, 0);
  57097. /**
  57098. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57099. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  57100. */
  57101. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  57102. this._isBillboardBased = true;
  57103. this._colorGradients = null;
  57104. this._sizeGradients = null;
  57105. this.id = name;
  57106. this.name = name;
  57107. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57108. this._engine = this._scene.getEngine();
  57109. if (!options.randomTextureSize) {
  57110. delete options.randomTextureSize;
  57111. }
  57112. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57113. var optionsAsNumber = options;
  57114. if (isFinite(optionsAsNumber)) {
  57115. fullOptions.capacity = optionsAsNumber;
  57116. }
  57117. this._capacity = fullOptions.capacity;
  57118. this._activeCount = fullOptions.capacity;
  57119. this._currentActiveCount = 0;
  57120. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57121. this._scene.particleSystems.push(this);
  57122. this._updateEffectOptions = {
  57123. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  57124. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57125. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57126. "angleRange", "radiusRange", "cellInfos"],
  57127. uniformBuffersNames: [],
  57128. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler"],
  57129. defines: "",
  57130. fallbacks: null,
  57131. onCompiled: null,
  57132. onError: null,
  57133. indexParameters: null,
  57134. maxSimultaneousLights: 0,
  57135. transformFeedbackVaryings: []
  57136. };
  57137. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57138. // Random data
  57139. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57140. var d = [];
  57141. for (var i = 0; i < maxTextureSize; ++i) {
  57142. d.push(Math.random());
  57143. d.push(Math.random());
  57144. d.push(Math.random());
  57145. d.push(Math.random());
  57146. }
  57147. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57148. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57149. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57150. d = [];
  57151. for (var i = 0; i < maxTextureSize; ++i) {
  57152. d.push(Math.random());
  57153. d.push(Math.random());
  57154. d.push(Math.random());
  57155. d.push(Math.random());
  57156. }
  57157. this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57158. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57159. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57160. this._randomTextureSize = maxTextureSize;
  57161. }
  57162. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57163. /**
  57164. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57165. */
  57166. get: function () {
  57167. if (!BABYLON.Engine.LastCreatedEngine) {
  57168. return false;
  57169. }
  57170. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57171. },
  57172. enumerable: true,
  57173. configurable: true
  57174. });
  57175. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57176. /**
  57177. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57178. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57179. */
  57180. get: function () {
  57181. if (this.particleEmitterType.direction1) {
  57182. return this.particleEmitterType.direction1;
  57183. }
  57184. return BABYLON.Vector3.Zero();
  57185. },
  57186. set: function (value) {
  57187. if (this.particleEmitterType.direction1) {
  57188. this.particleEmitterType.direction1 = value;
  57189. }
  57190. },
  57191. enumerable: true,
  57192. configurable: true
  57193. });
  57194. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57195. /**
  57196. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57197. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57198. */
  57199. get: function () {
  57200. if (this.particleEmitterType.direction2) {
  57201. return this.particleEmitterType.direction2;
  57202. }
  57203. return BABYLON.Vector3.Zero();
  57204. },
  57205. set: function (value) {
  57206. if (this.particleEmitterType.direction2) {
  57207. this.particleEmitterType.direction2 = value;
  57208. }
  57209. },
  57210. enumerable: true,
  57211. configurable: true
  57212. });
  57213. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57214. /**
  57215. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  57216. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57217. */
  57218. get: function () {
  57219. if (this.particleEmitterType.minEmitBox) {
  57220. return this.particleEmitterType.minEmitBox;
  57221. }
  57222. return BABYLON.Vector3.Zero();
  57223. },
  57224. set: function (value) {
  57225. if (this.particleEmitterType.minEmitBox) {
  57226. this.particleEmitterType.minEmitBox = value;
  57227. }
  57228. },
  57229. enumerable: true,
  57230. configurable: true
  57231. });
  57232. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57233. /**
  57234. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  57235. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57236. */
  57237. get: function () {
  57238. if (this.particleEmitterType.maxEmitBox) {
  57239. return this.particleEmitterType.maxEmitBox;
  57240. }
  57241. return BABYLON.Vector3.Zero();
  57242. },
  57243. set: function (value) {
  57244. if (this.particleEmitterType.maxEmitBox) {
  57245. this.particleEmitterType.maxEmitBox = value;
  57246. }
  57247. },
  57248. enumerable: true,
  57249. configurable: true
  57250. });
  57251. /**
  57252. * Gets the maximum number of particles active at the same time.
  57253. * @returns The max number of active particles.
  57254. */
  57255. GPUParticleSystem.prototype.getCapacity = function () {
  57256. return this._capacity;
  57257. };
  57258. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57259. /**
  57260. * Gets or set the number of active particles
  57261. */
  57262. get: function () {
  57263. return this._activeCount;
  57264. },
  57265. set: function (value) {
  57266. this._activeCount = Math.min(value, this._capacity);
  57267. },
  57268. enumerable: true,
  57269. configurable: true
  57270. });
  57271. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57272. /**
  57273. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57274. */
  57275. get: function () {
  57276. return this._isAnimationSheetEnabled;
  57277. },
  57278. enumerable: true,
  57279. configurable: true
  57280. });
  57281. /**
  57282. * Is this system ready to be used/rendered
  57283. * @return true if the system is ready
  57284. */
  57285. GPUParticleSystem.prototype.isReady = function () {
  57286. if (!this._updateEffect) {
  57287. this._recreateUpdateEffect();
  57288. this._recreateRenderEffect();
  57289. return false;
  57290. }
  57291. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57292. return false;
  57293. }
  57294. return true;
  57295. };
  57296. /**
  57297. * Gets Wether the system has been started.
  57298. * @returns True if it has been started, otherwise false.
  57299. */
  57300. GPUParticleSystem.prototype.isStarted = function () {
  57301. return this._started;
  57302. };
  57303. /**
  57304. * Starts the particle system and begins to emit.
  57305. */
  57306. GPUParticleSystem.prototype.start = function () {
  57307. this._started = true;
  57308. this._stopped = false;
  57309. this._preWarmDone = false;
  57310. };
  57311. /**
  57312. * Stops the particle system.
  57313. */
  57314. GPUParticleSystem.prototype.stop = function () {
  57315. this._stopped = true;
  57316. };
  57317. /**
  57318. * Remove all active particles
  57319. */
  57320. GPUParticleSystem.prototype.reset = function () {
  57321. this._releaseBuffers();
  57322. this._releaseVAOs();
  57323. this._currentActiveCount = 0;
  57324. this._targetIndex = 0;
  57325. };
  57326. /**
  57327. * Returns the string "GPUParticleSystem"
  57328. * @returns a string containing the class name
  57329. */
  57330. GPUParticleSystem.prototype.getClassName = function () {
  57331. return "GPUParticleSystem";
  57332. };
  57333. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57334. /**
  57335. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57336. */
  57337. get: function () {
  57338. return this._isBillboardBased;
  57339. },
  57340. set: function (value) {
  57341. if (this._isBillboardBased === value) {
  57342. return;
  57343. }
  57344. this._isBillboardBased = value;
  57345. this._releaseBuffers();
  57346. },
  57347. enumerable: true,
  57348. configurable: true
  57349. });
  57350. /**
  57351. * Gets the current list of color gradients.
  57352. * You must use addColorGradient and removeColorGradient to udpate this list
  57353. * @returns the list of color gradients
  57354. */
  57355. GPUParticleSystem.prototype.getColorGradients = function () {
  57356. return this._colorGradients;
  57357. };
  57358. /**
  57359. * Gets the current list of size gradients.
  57360. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57361. * @returns the list of size gradients
  57362. */
  57363. GPUParticleSystem.prototype.getSizeGradients = function () {
  57364. return this._sizeGradients;
  57365. };
  57366. /**
  57367. * Adds a new color gradient
  57368. * @param gradient defines the gradient to use (between 0 and 1)
  57369. * @param color defines the color to affect to the specified gradient
  57370. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57371. */
  57372. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57373. if (!this._colorGradients) {
  57374. this._colorGradients = [];
  57375. }
  57376. var colorGradient = new BABYLON.ColorGradient();
  57377. colorGradient.gradient = gradient;
  57378. colorGradient.color1 = color1;
  57379. this._colorGradients.push(colorGradient);
  57380. this._colorGradients.sort(function (a, b) {
  57381. if (a.gradient < b.gradient) {
  57382. return -1;
  57383. }
  57384. else if (a.gradient > b.gradient) {
  57385. return 1;
  57386. }
  57387. return 0;
  57388. });
  57389. if (this._colorGradientsTexture) {
  57390. this._colorGradientsTexture.dispose();
  57391. this._colorGradientsTexture = null;
  57392. }
  57393. this._releaseBuffers();
  57394. return this;
  57395. };
  57396. /**
  57397. * Remove a specific color gradient
  57398. * @param gradient defines the gradient to remove
  57399. */
  57400. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57401. if (!this._colorGradients) {
  57402. return this;
  57403. }
  57404. var index = 0;
  57405. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57406. var colorGradient = _a[_i];
  57407. if (colorGradient.gradient === gradient) {
  57408. this._colorGradients.splice(index, 1);
  57409. break;
  57410. }
  57411. index++;
  57412. }
  57413. if (this._colorGradientsTexture) {
  57414. this._colorGradientsTexture.dispose();
  57415. this._colorGradientsTexture = null;
  57416. }
  57417. this._releaseBuffers();
  57418. return this;
  57419. };
  57420. /**
  57421. * Adds a new size gradient
  57422. * @param gradient defines the gradient to use (between 0 and 1)
  57423. * @param factor defines the size factor to affect to the specified gradient
  57424. */
  57425. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57426. if (!this._sizeGradients) {
  57427. this._sizeGradients = [];
  57428. }
  57429. var sizeGradient = new BABYLON.FactorGradient();
  57430. sizeGradient.gradient = gradient;
  57431. sizeGradient.factor1 = factor;
  57432. this._sizeGradients.push(sizeGradient);
  57433. this._sizeGradients.sort(function (a, b) {
  57434. if (a.gradient < b.gradient) {
  57435. return -1;
  57436. }
  57437. else if (a.gradient > b.gradient) {
  57438. return 1;
  57439. }
  57440. return 0;
  57441. });
  57442. if (this._sizeGradientsTexture) {
  57443. this._sizeGradientsTexture.dispose();
  57444. this._sizeGradientsTexture = null;
  57445. }
  57446. this._releaseBuffers();
  57447. return this;
  57448. };
  57449. /**
  57450. * Remove a specific size gradient
  57451. * @param gradient defines the gradient to remove
  57452. */
  57453. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57454. if (!this._sizeGradients) {
  57455. return this;
  57456. }
  57457. var index = 0;
  57458. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  57459. var sizeGradient = _a[_i];
  57460. if (sizeGradient.gradient === gradient) {
  57461. this._sizeGradients.splice(index, 1);
  57462. break;
  57463. }
  57464. index++;
  57465. }
  57466. if (this._sizeGradientsTexture) {
  57467. this._sizeGradientsTexture.dispose();
  57468. this._sizeGradientsTexture = null;
  57469. }
  57470. this._releaseBuffers();
  57471. return this;
  57472. };
  57473. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57474. var updateVertexBuffers = {};
  57475. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57476. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57477. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57478. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57479. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57480. var offset = 12;
  57481. if (!this._colorGradientsTexture) {
  57482. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57483. offset += 4;
  57484. }
  57485. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57486. offset += 3;
  57487. if (!this._isBillboardBased) {
  57488. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57489. offset += 3;
  57490. }
  57491. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57492. offset += 2;
  57493. if (this._isAnimationSheetEnabled) {
  57494. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57495. offset += 1;
  57496. }
  57497. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57498. this._engine.bindArrayBuffer(null);
  57499. return vao;
  57500. };
  57501. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57502. var renderVertexBuffers = {};
  57503. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57504. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57505. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57506. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57507. var offset = 12;
  57508. if (!this._colorGradientsTexture) {
  57509. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57510. offset += 4;
  57511. }
  57512. offset += 3; // Direction
  57513. if (!this._isBillboardBased) {
  57514. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57515. offset += 3;
  57516. }
  57517. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2, this._attributesStrideSize, true);
  57518. offset += 2;
  57519. if (this._isAnimationSheetEnabled) {
  57520. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57521. offset += 1;
  57522. }
  57523. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57524. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57525. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57526. this._engine.bindArrayBuffer(null);
  57527. return vao;
  57528. };
  57529. GPUParticleSystem.prototype._initialize = function (force) {
  57530. if (force === void 0) { force = false; }
  57531. if (this._buffer0 && !force) {
  57532. return;
  57533. }
  57534. var engine = this._scene.getEngine();
  57535. var data = new Array();
  57536. if (!this.isBillboardBased) {
  57537. this._attributesStrideSize += 3;
  57538. }
  57539. if (this._colorGradientsTexture) {
  57540. this._attributesStrideSize -= 4;
  57541. }
  57542. if (this._isAnimationSheetEnabled) {
  57543. this._attributesStrideSize += 1;
  57544. }
  57545. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57546. // position
  57547. data.push(0.0);
  57548. data.push(0.0);
  57549. data.push(0.0);
  57550. // Age and life
  57551. data.push(0.0); // create the particle as a dead one to create a new one at start
  57552. data.push(0.0);
  57553. // Seed
  57554. data.push(Math.random());
  57555. data.push(Math.random());
  57556. data.push(Math.random());
  57557. data.push(Math.random());
  57558. // Size
  57559. data.push(0.0);
  57560. data.push(0.0);
  57561. data.push(0.0);
  57562. if (!this._colorGradientsTexture) {
  57563. // color
  57564. data.push(0.0);
  57565. data.push(0.0);
  57566. data.push(0.0);
  57567. data.push(0.0);
  57568. }
  57569. // direction
  57570. data.push(0.0);
  57571. data.push(0.0);
  57572. data.push(0.0);
  57573. if (!this.isBillboardBased) {
  57574. // initialDirection
  57575. data.push(0.0);
  57576. data.push(0.0);
  57577. data.push(0.0);
  57578. }
  57579. // angle
  57580. data.push(0.0);
  57581. data.push(0.0);
  57582. if (this._isAnimationSheetEnabled) {
  57583. data.push(0.0);
  57584. }
  57585. }
  57586. // Sprite data
  57587. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57588. -0.5, 0.5, 0, 1,
  57589. -0.5, -0.5, 0, 0,
  57590. 0.5, -0.5, 1, 0]);
  57591. // Buffers
  57592. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57593. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57594. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57595. // Update VAO
  57596. this._updateVAO = [];
  57597. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57598. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57599. // Render VAO
  57600. this._renderVAO = [];
  57601. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57602. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57603. // Links
  57604. this._sourceBuffer = this._buffer0;
  57605. this._targetBuffer = this._buffer1;
  57606. };
  57607. /** @hidden */
  57608. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57609. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57610. if (this._isBillboardBased) {
  57611. defines += "\n#define BILLBOARD";
  57612. }
  57613. if (this._colorGradientsTexture) {
  57614. defines += "\n#define COLORGRADIENTS";
  57615. }
  57616. if (this._sizeGradientsTexture) {
  57617. defines += "\n#define SIZEGRADIENTS";
  57618. }
  57619. if (this.isAnimationSheetEnabled) {
  57620. defines += "\n#define ANIMATESHEET";
  57621. }
  57622. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57623. return;
  57624. }
  57625. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57626. if (!this._colorGradientsTexture) {
  57627. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57628. }
  57629. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57630. if (!this._isBillboardBased) {
  57631. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57632. }
  57633. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57634. if (this.isAnimationSheetEnabled) {
  57635. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57636. }
  57637. this._updateEffectOptions.defines = defines;
  57638. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57639. };
  57640. /** @hidden */
  57641. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57642. var defines = "";
  57643. if (this._scene.clipPlane) {
  57644. defines = "\n#define CLIPPLANE";
  57645. }
  57646. if (this._isBillboardBased) {
  57647. defines += "\n#define BILLBOARD";
  57648. switch (this.billboardMode) {
  57649. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57650. defines += "\n#define BILLBOARDY";
  57651. break;
  57652. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57653. default:
  57654. break;
  57655. }
  57656. }
  57657. if (this._colorGradientsTexture) {
  57658. defines += "\n#define COLORGRADIENTS";
  57659. }
  57660. if (this.isAnimationSheetEnabled) {
  57661. defines += "\n#define ANIMATESHEET";
  57662. }
  57663. if (this._renderEffect && this._renderEffect.defines === defines) {
  57664. return;
  57665. }
  57666. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57667. };
  57668. /**
  57669. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57670. * @param preWarm defines if we are in the pre-warmimg phase
  57671. */
  57672. GPUParticleSystem.prototype.animate = function (preWarm) {
  57673. if (preWarm === void 0) { preWarm = false; }
  57674. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57675. this._actualFrame += this._timeDelta;
  57676. if (!this._stopped) {
  57677. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57678. this.stop();
  57679. }
  57680. }
  57681. };
  57682. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57683. if (!this._sizeGradients || !this._sizeGradients.length || this._sizeGradientsTexture) {
  57684. return;
  57685. }
  57686. var textureWidth = 256;
  57687. var data = new Float32Array(textureWidth);
  57688. for (var x = 0; x < textureWidth; x++) {
  57689. var ratio = x / textureWidth;
  57690. BABYLON.Tools.GetCurrentGradient(ratio, this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57691. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57692. });
  57693. }
  57694. this._sizeGradientsTexture = BABYLON.RawTexture.CreateRTexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57695. };
  57696. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57697. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57698. return;
  57699. }
  57700. var textureWidth = 256;
  57701. var data = new Uint8Array(textureWidth * 4);
  57702. var tmpColor = BABYLON.Tmp.Color4[0];
  57703. for (var x = 0; x < textureWidth; x++) {
  57704. var ratio = x / textureWidth;
  57705. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57706. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57707. data[x * 4] = tmpColor.r * 255;
  57708. data[x * 4 + 1] = tmpColor.g * 255;
  57709. data[x * 4 + 2] = tmpColor.b * 255;
  57710. data[x * 4 + 3] = tmpColor.a * 255;
  57711. });
  57712. }
  57713. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57714. };
  57715. /**
  57716. * Renders the particle system in its current state
  57717. * @param preWarm defines if the system should only update the particles but not render them
  57718. * @returns the current number of particles
  57719. */
  57720. GPUParticleSystem.prototype.render = function (preWarm) {
  57721. if (preWarm === void 0) { preWarm = false; }
  57722. if (!this._started) {
  57723. return 0;
  57724. }
  57725. this._createColorGradientTexture();
  57726. this._createSizeGradientTexture();
  57727. this._recreateUpdateEffect();
  57728. this._recreateRenderEffect();
  57729. if (!this.isReady()) {
  57730. return 0;
  57731. }
  57732. if (!preWarm) {
  57733. if (!this._preWarmDone && this.preWarmCycles) {
  57734. for (var index = 0; index < this.preWarmCycles; index++) {
  57735. this.animate(true);
  57736. this.render(true);
  57737. }
  57738. this._preWarmDone = true;
  57739. }
  57740. if (this._currentRenderId === this._scene.getRenderId()) {
  57741. return 0;
  57742. }
  57743. this._currentRenderId = this._scene.getRenderId();
  57744. }
  57745. // Get everything ready to render
  57746. this._initialize();
  57747. this._accumulatedCount += this.emitRate * this._timeDelta;
  57748. if (this._accumulatedCount > 1) {
  57749. var intPart = this._accumulatedCount | 0;
  57750. this._accumulatedCount -= intPart;
  57751. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57752. }
  57753. if (!this._currentActiveCount) {
  57754. return 0;
  57755. }
  57756. // Enable update effect
  57757. this._engine.enableEffect(this._updateEffect);
  57758. this._engine.setState(false);
  57759. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57760. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57761. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57762. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57763. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57764. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57765. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57766. if (!this._colorGradientsTexture) {
  57767. this._updateEffect.setDirectColor4("color1", this.color1);
  57768. this._updateEffect.setDirectColor4("color2", this.color2);
  57769. }
  57770. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57771. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57772. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57773. this._updateEffect.setVector3("gravity", this.gravity);
  57774. if (this._sizeGradientsTexture) {
  57775. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57776. }
  57777. if (this.particleEmitterType) {
  57778. this.particleEmitterType.applyToShader(this._updateEffect);
  57779. }
  57780. if (this._isAnimationSheetEnabled) {
  57781. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  57782. }
  57783. var emitterWM;
  57784. if (this.emitter.position) {
  57785. var emitterMesh = this.emitter;
  57786. emitterWM = emitterMesh.getWorldMatrix();
  57787. }
  57788. else {
  57789. var emitterPosition = this.emitter;
  57790. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57791. }
  57792. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57793. // Bind source VAO
  57794. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57795. // Update
  57796. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57797. this._engine.setRasterizerState(false);
  57798. this._engine.beginTransformFeedback();
  57799. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57800. this._engine.endTransformFeedback();
  57801. this._engine.setRasterizerState(true);
  57802. this._engine.bindTransformFeedbackBuffer(null);
  57803. if (!preWarm) {
  57804. // Enable render effect
  57805. this._engine.enableEffect(this._renderEffect);
  57806. var viewMatrix = this._scene.getViewMatrix();
  57807. this._renderEffect.setMatrix("view", viewMatrix);
  57808. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57809. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57810. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  57811. if (this._colorGradientsTexture) {
  57812. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57813. }
  57814. else {
  57815. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57816. }
  57817. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57818. var baseSize = this.particleTexture.getBaseSize();
  57819. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57820. }
  57821. if (this._isBillboardBased) {
  57822. var camera = this._scene.activeCamera;
  57823. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  57824. }
  57825. if (this._scene.clipPlane) {
  57826. var clipPlane = this._scene.clipPlane;
  57827. var invView = viewMatrix.clone();
  57828. invView.invert();
  57829. this._renderEffect.setMatrix("invView", invView);
  57830. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57831. }
  57832. // Draw order
  57833. switch (this.blendMode) {
  57834. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57835. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57836. break;
  57837. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57838. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57839. break;
  57840. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57841. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57842. break;
  57843. }
  57844. if (this.forceDepthWrite) {
  57845. this._engine.setDepthWrite(true);
  57846. }
  57847. // Bind source VAO
  57848. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57849. // Render
  57850. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57851. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57852. }
  57853. // Switch VAOs
  57854. this._targetIndex++;
  57855. if (this._targetIndex === 2) {
  57856. this._targetIndex = 0;
  57857. }
  57858. // Switch buffers
  57859. var tmpBuffer = this._sourceBuffer;
  57860. this._sourceBuffer = this._targetBuffer;
  57861. this._targetBuffer = tmpBuffer;
  57862. return this._currentActiveCount;
  57863. };
  57864. /**
  57865. * Rebuilds the particle system
  57866. */
  57867. GPUParticleSystem.prototype.rebuild = function () {
  57868. this._initialize(true);
  57869. };
  57870. GPUParticleSystem.prototype._releaseBuffers = function () {
  57871. if (this._buffer0) {
  57872. this._buffer0.dispose();
  57873. this._buffer0 = null;
  57874. }
  57875. if (this._buffer1) {
  57876. this._buffer1.dispose();
  57877. this._buffer1 = null;
  57878. }
  57879. if (this._spriteBuffer) {
  57880. this._spriteBuffer.dispose();
  57881. this._spriteBuffer = null;
  57882. }
  57883. };
  57884. GPUParticleSystem.prototype._releaseVAOs = function () {
  57885. if (!this._updateVAO) {
  57886. return;
  57887. }
  57888. for (var index = 0; index < this._updateVAO.length; index++) {
  57889. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57890. }
  57891. this._updateVAO = [];
  57892. for (var index = 0; index < this._renderVAO.length; index++) {
  57893. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57894. }
  57895. this._renderVAO = [];
  57896. };
  57897. /**
  57898. * Disposes the particle system and free the associated resources
  57899. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57900. */
  57901. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57902. if (disposeTexture === void 0) { disposeTexture = true; }
  57903. var index = this._scene.particleSystems.indexOf(this);
  57904. if (index > -1) {
  57905. this._scene.particleSystems.splice(index, 1);
  57906. }
  57907. this._releaseBuffers();
  57908. this._releaseVAOs();
  57909. if (this._colorGradientsTexture) {
  57910. this._colorGradientsTexture.dispose();
  57911. this._colorGradientsTexture = null;
  57912. }
  57913. if (this._sizeGradientsTexture) {
  57914. this._sizeGradientsTexture.dispose();
  57915. this._sizeGradientsTexture = null;
  57916. }
  57917. if (this._randomTexture) {
  57918. this._randomTexture.dispose();
  57919. this._randomTexture = null;
  57920. }
  57921. if (this._randomTexture2) {
  57922. this._randomTexture2.dispose();
  57923. this._randomTexture2 = null;
  57924. }
  57925. if (disposeTexture && this.particleTexture) {
  57926. this.particleTexture.dispose();
  57927. this.particleTexture = null;
  57928. }
  57929. // Callback
  57930. this.onDisposeObservable.notifyObservers(this);
  57931. this.onDisposeObservable.clear();
  57932. };
  57933. /**
  57934. * Clones the particle system.
  57935. * @param name The name of the cloned object
  57936. * @param newEmitter The new emitter to use
  57937. * @returns the cloned particle system
  57938. */
  57939. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57940. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57941. BABYLON.Tools.DeepCopy(this, result);
  57942. if (newEmitter === undefined) {
  57943. newEmitter = this.emitter;
  57944. }
  57945. result.emitter = newEmitter;
  57946. if (this.particleTexture) {
  57947. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57948. }
  57949. return result;
  57950. };
  57951. /**
  57952. * Serializes the particle system to a JSON object.
  57953. * @returns the JSON object
  57954. */
  57955. GPUParticleSystem.prototype.serialize = function () {
  57956. var serializationObject = {};
  57957. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  57958. serializationObject.activeParticleCount = this.activeParticleCount;
  57959. return serializationObject;
  57960. };
  57961. /**
  57962. * Parses a JSON object to create a GPU particle system.
  57963. * @param parsedParticleSystem The JSON object to parse
  57964. * @param scene The scene to create the particle system in
  57965. * @param rootUrl The root url to use to load external dependencies like texture
  57966. * @returns the parsed GPU particle system
  57967. */
  57968. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57969. var name = parsedParticleSystem.name;
  57970. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57971. if (parsedParticleSystem.activeParticleCount) {
  57972. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57973. }
  57974. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57975. return particleSystem;
  57976. };
  57977. return GPUParticleSystem;
  57978. }());
  57979. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57980. })(BABYLON || (BABYLON = {}));
  57981. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57982. var BABYLON;
  57983. (function (BABYLON) {
  57984. /**
  57985. * Represents one particle of a solid particle system.
  57986. */
  57987. var SolidParticle = /** @class */ (function () {
  57988. /**
  57989. * Creates a Solid Particle object.
  57990. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57991. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57992. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57993. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57994. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57995. * @param shapeId (integer) is the model shape identifier in the SPS.
  57996. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57997. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57998. */
  57999. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58000. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58001. /**
  58002. * particle global index
  58003. */
  58004. this.idx = 0;
  58005. /**
  58006. * The color of the particle
  58007. */
  58008. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58009. /**
  58010. * The world space position of the particle.
  58011. */
  58012. this.position = BABYLON.Vector3.Zero();
  58013. /**
  58014. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58015. */
  58016. this.rotation = BABYLON.Vector3.Zero();
  58017. /**
  58018. * The scaling of the particle.
  58019. */
  58020. this.scaling = BABYLON.Vector3.One();
  58021. /**
  58022. * The uvs of the particle.
  58023. */
  58024. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58025. /**
  58026. * The current speed of the particle.
  58027. */
  58028. this.velocity = BABYLON.Vector3.Zero();
  58029. /**
  58030. * The pivot point in the particle local space.
  58031. */
  58032. this.pivot = BABYLON.Vector3.Zero();
  58033. /**
  58034. * Must the particle be translated from its pivot point in its local space ?
  58035. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58036. * Default : false
  58037. */
  58038. this.translateFromPivot = false;
  58039. /**
  58040. * Is the particle active or not ?
  58041. */
  58042. this.alive = true;
  58043. /**
  58044. * Is the particle visible or not ?
  58045. */
  58046. this.isVisible = true;
  58047. /**
  58048. * Index of this particle in the global "positions" array (Internal use)
  58049. */
  58050. this._pos = 0;
  58051. /**
  58052. * Index of this particle in the global "indices" array (Internal use)
  58053. */
  58054. this._ind = 0;
  58055. /**
  58056. * ModelShape id of this particle
  58057. */
  58058. this.shapeId = 0;
  58059. /**
  58060. * Index of the particle in its shape id (Internal use)
  58061. */
  58062. this.idxInShape = 0;
  58063. /**
  58064. * Still set as invisible in order to skip useless computations (Internal use)
  58065. */
  58066. this._stillInvisible = false;
  58067. /**
  58068. * Last computed particle rotation matrix
  58069. */
  58070. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58071. /**
  58072. * Parent particle Id, if any.
  58073. * Default null.
  58074. */
  58075. this.parentId = null;
  58076. /**
  58077. * Internal global position in the SPS.
  58078. */
  58079. this._globalPosition = BABYLON.Vector3.Zero();
  58080. this.idx = particleIndex;
  58081. this._pos = positionIndex;
  58082. this._ind = indiceIndex;
  58083. this._model = model;
  58084. this.shapeId = shapeId;
  58085. this.idxInShape = idxInShape;
  58086. this._sps = sps;
  58087. if (modelBoundingInfo) {
  58088. this._modelBoundingInfo = modelBoundingInfo;
  58089. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58090. }
  58091. }
  58092. Object.defineProperty(SolidParticle.prototype, "scale", {
  58093. /**
  58094. * Legacy support, changed scale to scaling
  58095. */
  58096. get: function () {
  58097. return this.scaling;
  58098. },
  58099. /**
  58100. * Legacy support, changed scale to scaling
  58101. */
  58102. set: function (scale) {
  58103. this.scaling = scale;
  58104. },
  58105. enumerable: true,
  58106. configurable: true
  58107. });
  58108. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58109. /**
  58110. * Legacy support, changed quaternion to rotationQuaternion
  58111. */
  58112. get: function () {
  58113. return this.rotationQuaternion;
  58114. },
  58115. /**
  58116. * Legacy support, changed quaternion to rotationQuaternion
  58117. */
  58118. set: function (q) {
  58119. this.rotationQuaternion = q;
  58120. },
  58121. enumerable: true,
  58122. configurable: true
  58123. });
  58124. /**
  58125. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58126. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58127. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58128. * @returns true if it intersects
  58129. */
  58130. SolidParticle.prototype.intersectsMesh = function (target) {
  58131. if (!this._boundingInfo || !target._boundingInfo) {
  58132. return false;
  58133. }
  58134. if (this._sps._bSphereOnly) {
  58135. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58136. }
  58137. return this._boundingInfo.intersects(target._boundingInfo, false);
  58138. };
  58139. return SolidParticle;
  58140. }());
  58141. BABYLON.SolidParticle = SolidParticle;
  58142. /**
  58143. * Represents the shape of the model used by one particle of a solid particle system.
  58144. * SPS internal tool, don't use it manually.
  58145. */
  58146. var ModelShape = /** @class */ (function () {
  58147. /**
  58148. * 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.
  58149. * SPS internal tool, don't use it manually.
  58150. * @hidden
  58151. */
  58152. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58153. /**
  58154. * length of the shape in the model indices array (internal use)
  58155. */
  58156. this._indicesLength = 0;
  58157. this.shapeID = id;
  58158. this._shape = shape;
  58159. this._indicesLength = indicesLength;
  58160. this._shapeUV = shapeUV;
  58161. this._positionFunction = posFunction;
  58162. this._vertexFunction = vtxFunction;
  58163. }
  58164. return ModelShape;
  58165. }());
  58166. BABYLON.ModelShape = ModelShape;
  58167. /**
  58168. * Represents a Depth Sorted Particle in the solid particle system.
  58169. */
  58170. var DepthSortedParticle = /** @class */ (function () {
  58171. function DepthSortedParticle() {
  58172. /**
  58173. * Index of the particle in the "indices" array
  58174. */
  58175. this.ind = 0;
  58176. /**
  58177. * Length of the particle shape in the "indices" array
  58178. */
  58179. this.indicesLength = 0;
  58180. /**
  58181. * Squared distance from the particle to the camera
  58182. */
  58183. this.sqDistance = 0.0;
  58184. }
  58185. return DepthSortedParticle;
  58186. }());
  58187. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58188. })(BABYLON || (BABYLON = {}));
  58189. //# sourceMappingURL=babylon.solidParticle.js.map
  58190. var BABYLON;
  58191. (function (BABYLON) {
  58192. /**
  58193. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58194. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  58195. * The SPS is also a particle system. It provides some methods to manage the particles.
  58196. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58197. *
  58198. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58199. */
  58200. var SolidParticleSystem = /** @class */ (function () {
  58201. /**
  58202. * Creates a SPS (Solid Particle System) object.
  58203. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58204. * @param scene (Scene) is the scene in which the SPS is added.
  58205. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58206. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58207. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58208. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58209. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58210. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58211. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58212. */
  58213. function SolidParticleSystem(name, scene, options) {
  58214. /**
  58215. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58216. * Example : var p = SPS.particles[i];
  58217. */
  58218. this.particles = new Array();
  58219. /**
  58220. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58221. */
  58222. this.nbParticles = 0;
  58223. /**
  58224. * If the particles must ever face the camera (default false). Useful for planar particles.
  58225. */
  58226. this.billboard = false;
  58227. /**
  58228. * Recompute normals when adding a shape
  58229. */
  58230. this.recomputeNormals = true;
  58231. /**
  58232. * This a counter ofr your own usage. It's not set by any SPS functions.
  58233. */
  58234. this.counter = 0;
  58235. /**
  58236. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58237. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58238. */
  58239. this.vars = {};
  58240. /**
  58241. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58242. */
  58243. this._bSphereOnly = false;
  58244. /**
  58245. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58246. */
  58247. this._bSphereRadiusFactor = 1.0;
  58248. this._positions = new Array();
  58249. this._indices = new Array();
  58250. this._normals = new Array();
  58251. this._colors = new Array();
  58252. this._uvs = new Array();
  58253. this._index = 0; // indices index
  58254. this._updatable = true;
  58255. this._pickable = false;
  58256. this._isVisibilityBoxLocked = false;
  58257. this._alwaysVisible = false;
  58258. this._depthSort = false;
  58259. this._shapeCounter = 0;
  58260. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58261. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58262. this._computeParticleColor = true;
  58263. this._computeParticleTexture = true;
  58264. this._computeParticleRotation = true;
  58265. this._computeParticleVertex = false;
  58266. this._computeBoundingBox = false;
  58267. this._depthSortParticles = true;
  58268. this._cam_axisZ = BABYLON.Vector3.Zero();
  58269. this._cam_axisY = BABYLON.Vector3.Zero();
  58270. this._cam_axisX = BABYLON.Vector3.Zero();
  58271. this._axisZ = BABYLON.Axis.Z;
  58272. this._camDir = BABYLON.Vector3.Zero();
  58273. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58274. this._rotMatrix = new BABYLON.Matrix();
  58275. this._invertMatrix = new BABYLON.Matrix();
  58276. this._rotated = BABYLON.Vector3.Zero();
  58277. this._quaternion = new BABYLON.Quaternion();
  58278. this._vertex = BABYLON.Vector3.Zero();
  58279. this._normal = BABYLON.Vector3.Zero();
  58280. this._yaw = 0.0;
  58281. this._pitch = 0.0;
  58282. this._roll = 0.0;
  58283. this._halfroll = 0.0;
  58284. this._halfpitch = 0.0;
  58285. this._halfyaw = 0.0;
  58286. this._sinRoll = 0.0;
  58287. this._cosRoll = 0.0;
  58288. this._sinPitch = 0.0;
  58289. this._cosPitch = 0.0;
  58290. this._sinYaw = 0.0;
  58291. this._cosYaw = 0.0;
  58292. this._mustUnrotateFixedNormals = false;
  58293. this._minimum = BABYLON.Vector3.Zero();
  58294. this._maximum = BABYLON.Vector3.Zero();
  58295. this._minBbox = BABYLON.Vector3.Zero();
  58296. this._maxBbox = BABYLON.Vector3.Zero();
  58297. this._particlesIntersect = false;
  58298. this._depthSortFunction = function (p1, p2) {
  58299. return (p2.sqDistance - p1.sqDistance);
  58300. };
  58301. this._needs32Bits = false;
  58302. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58303. this._scaledPivot = BABYLON.Vector3.Zero();
  58304. this._particleHasParent = false;
  58305. this.name = name;
  58306. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58307. this._camera = scene.activeCamera;
  58308. this._pickable = options ? options.isPickable : false;
  58309. this._depthSort = options ? options.enableDepthSort : false;
  58310. this._particlesIntersect = options ? options.particleIntersection : false;
  58311. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58312. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58313. if (options && options.updatable !== undefined) {
  58314. this._updatable = options.updatable;
  58315. }
  58316. else {
  58317. this._updatable = true;
  58318. }
  58319. if (this._pickable) {
  58320. this.pickedParticles = [];
  58321. }
  58322. if (this._depthSort) {
  58323. this.depthSortedParticles = [];
  58324. }
  58325. }
  58326. /**
  58327. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58328. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58329. * @returns the created mesh
  58330. */
  58331. SolidParticleSystem.prototype.buildMesh = function () {
  58332. if (this.nbParticles === 0) {
  58333. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58334. this.addShape(triangle, 1);
  58335. triangle.dispose();
  58336. }
  58337. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58338. this._positions32 = new Float32Array(this._positions);
  58339. this._uvs32 = new Float32Array(this._uvs);
  58340. this._colors32 = new Float32Array(this._colors);
  58341. if (this.recomputeNormals) {
  58342. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58343. }
  58344. this._normals32 = new Float32Array(this._normals);
  58345. this._fixedNormal32 = new Float32Array(this._normals);
  58346. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58347. this._unrotateFixedNormals();
  58348. }
  58349. var vertexData = new BABYLON.VertexData();
  58350. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58351. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58352. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58353. if (this._uvs32.length > 0) {
  58354. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58355. }
  58356. if (this._colors32.length > 0) {
  58357. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58358. }
  58359. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58360. vertexData.applyToMesh(mesh, this._updatable);
  58361. this.mesh = mesh;
  58362. this.mesh.isPickable = this._pickable;
  58363. // free memory
  58364. if (!this._depthSort) {
  58365. this._indices = null;
  58366. }
  58367. this._positions = null;
  58368. this._normals = null;
  58369. this._uvs = null;
  58370. this._colors = null;
  58371. if (!this._updatable) {
  58372. this.particles.length = 0;
  58373. }
  58374. return mesh;
  58375. };
  58376. /**
  58377. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58378. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58379. * Thus the particles generated from `digest()` have their property `position` set yet.
  58380. * @param mesh ( Mesh ) is the mesh to be digested
  58381. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  58382. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58383. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58384. * @returns the current SPS
  58385. */
  58386. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58387. var size = (options && options.facetNb) || 1;
  58388. var number = (options && options.number) || 0;
  58389. var delta = (options && options.delta) || 0;
  58390. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58391. var meshInd = mesh.getIndices();
  58392. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58393. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58394. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58395. var f = 0; // facet counter
  58396. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58397. // compute size from number
  58398. if (number) {
  58399. number = (number > totalFacets) ? totalFacets : number;
  58400. size = Math.round(totalFacets / number);
  58401. delta = 0;
  58402. }
  58403. else {
  58404. size = (size > totalFacets) ? totalFacets : size;
  58405. }
  58406. var facetPos = []; // submesh positions
  58407. var facetInd = []; // submesh indices
  58408. var facetUV = []; // submesh UV
  58409. var facetCol = []; // submesh colors
  58410. var barycenter = BABYLON.Vector3.Zero();
  58411. var sizeO = size;
  58412. while (f < totalFacets) {
  58413. size = sizeO + Math.floor((1 + delta) * Math.random());
  58414. if (f > totalFacets - size) {
  58415. size = totalFacets - f;
  58416. }
  58417. // reset temp arrays
  58418. facetPos.length = 0;
  58419. facetInd.length = 0;
  58420. facetUV.length = 0;
  58421. facetCol.length = 0;
  58422. // iterate over "size" facets
  58423. var fi = 0;
  58424. for (var j = f * 3; j < (f + size) * 3; j++) {
  58425. facetInd.push(fi);
  58426. var i = meshInd[j];
  58427. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58428. if (meshUV) {
  58429. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58430. }
  58431. if (meshCol) {
  58432. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58433. }
  58434. fi++;
  58435. }
  58436. // create a model shape for each single particle
  58437. var idx = this.nbParticles;
  58438. var shape = this._posToShape(facetPos);
  58439. var shapeUV = this._uvsToShapeUV(facetUV);
  58440. // compute the barycenter of the shape
  58441. var v;
  58442. for (v = 0; v < shape.length; v++) {
  58443. barycenter.addInPlace(shape[v]);
  58444. }
  58445. barycenter.scaleInPlace(1 / shape.length);
  58446. // shift the shape from its barycenter to the origin
  58447. for (v = 0; v < shape.length; v++) {
  58448. shape[v].subtractInPlace(barycenter);
  58449. }
  58450. var bInfo;
  58451. if (this._particlesIntersect) {
  58452. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58453. }
  58454. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58455. // add the particle in the SPS
  58456. var currentPos = this._positions.length;
  58457. var currentInd = this._indices.length;
  58458. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58459. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58460. // initialize the particle position
  58461. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58462. this._index += shape.length;
  58463. idx++;
  58464. this.nbParticles++;
  58465. this._shapeCounter++;
  58466. f += size;
  58467. }
  58468. return this;
  58469. };
  58470. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58471. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58472. var index = 0;
  58473. var idx = 0;
  58474. for (var p = 0; p < this.particles.length; p++) {
  58475. this._particle = this.particles[p];
  58476. this._shape = this._particle._model._shape;
  58477. if (this._particle.rotationQuaternion) {
  58478. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58479. }
  58480. else {
  58481. this._yaw = this._particle.rotation.y;
  58482. this._pitch = this._particle.rotation.x;
  58483. this._roll = this._particle.rotation.z;
  58484. this._quaternionRotationYPR();
  58485. }
  58486. this._quaternionToRotationMatrix();
  58487. this._rotMatrix.invertToRef(this._invertMatrix);
  58488. for (var pt = 0; pt < this._shape.length; pt++) {
  58489. idx = index + pt * 3;
  58490. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58491. this._fixedNormal32[idx] = this._normal.x;
  58492. this._fixedNormal32[idx + 1] = this._normal.y;
  58493. this._fixedNormal32[idx + 2] = this._normal.z;
  58494. }
  58495. index = idx + 3;
  58496. }
  58497. };
  58498. //reset copy
  58499. SolidParticleSystem.prototype._resetCopy = function () {
  58500. this._copy.position.x = 0;
  58501. this._copy.position.y = 0;
  58502. this._copy.position.z = 0;
  58503. this._copy.rotation.x = 0;
  58504. this._copy.rotation.y = 0;
  58505. this._copy.rotation.z = 0;
  58506. this._copy.rotationQuaternion = null;
  58507. this._copy.scaling.x = 1.0;
  58508. this._copy.scaling.y = 1.0;
  58509. this._copy.scaling.z = 1.0;
  58510. this._copy.uvs.x = 0;
  58511. this._copy.uvs.y = 0;
  58512. this._copy.uvs.z = 1.0;
  58513. this._copy.uvs.w = 1.0;
  58514. this._copy.color = null;
  58515. this._copy.translateFromPivot = false;
  58516. };
  58517. // _meshBuilder : inserts the shape model in the global SPS mesh
  58518. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58519. var i;
  58520. var u = 0;
  58521. var c = 0;
  58522. var n = 0;
  58523. this._resetCopy();
  58524. if (options && options.positionFunction) { // call to custom positionFunction
  58525. options.positionFunction(this._copy, idx, idxInShape);
  58526. this._mustUnrotateFixedNormals = true;
  58527. }
  58528. if (this._copy.rotationQuaternion) {
  58529. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58530. }
  58531. else {
  58532. this._yaw = this._copy.rotation.y;
  58533. this._pitch = this._copy.rotation.x;
  58534. this._roll = this._copy.rotation.z;
  58535. this._quaternionRotationYPR();
  58536. }
  58537. this._quaternionToRotationMatrix();
  58538. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58539. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58540. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58541. if (this._copy.translateFromPivot) {
  58542. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58543. }
  58544. else {
  58545. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58546. }
  58547. for (i = 0; i < shape.length; i++) {
  58548. this._vertex.x = shape[i].x;
  58549. this._vertex.y = shape[i].y;
  58550. this._vertex.z = shape[i].z;
  58551. if (options && options.vertexFunction) {
  58552. options.vertexFunction(this._copy, this._vertex, i);
  58553. }
  58554. this._vertex.x *= this._copy.scaling.x;
  58555. this._vertex.y *= this._copy.scaling.y;
  58556. this._vertex.z *= this._copy.scaling.z;
  58557. this._vertex.x -= this._scaledPivot.x;
  58558. this._vertex.y -= this._scaledPivot.y;
  58559. this._vertex.z -= this._scaledPivot.z;
  58560. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58561. this._rotated.addInPlace(this._pivotBackTranslation);
  58562. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58563. if (meshUV) {
  58564. 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);
  58565. u += 2;
  58566. }
  58567. if (this._copy.color) {
  58568. this._color = this._copy.color;
  58569. }
  58570. else if (meshCol && meshCol[c] !== undefined) {
  58571. this._color.r = meshCol[c];
  58572. this._color.g = meshCol[c + 1];
  58573. this._color.b = meshCol[c + 2];
  58574. this._color.a = meshCol[c + 3];
  58575. }
  58576. else {
  58577. this._color.r = 1.0;
  58578. this._color.g = 1.0;
  58579. this._color.b = 1.0;
  58580. this._color.a = 1.0;
  58581. }
  58582. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58583. c += 4;
  58584. if (!this.recomputeNormals && meshNor) {
  58585. this._normal.x = meshNor[n];
  58586. this._normal.y = meshNor[n + 1];
  58587. this._normal.z = meshNor[n + 2];
  58588. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58589. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58590. n += 3;
  58591. }
  58592. }
  58593. for (i = 0; i < meshInd.length; i++) {
  58594. var current_ind = p + meshInd[i];
  58595. indices.push(current_ind);
  58596. if (current_ind > 65535) {
  58597. this._needs32Bits = true;
  58598. }
  58599. }
  58600. if (this._pickable) {
  58601. var nbfaces = meshInd.length / 3;
  58602. for (i = 0; i < nbfaces; i++) {
  58603. this.pickedParticles.push({ idx: idx, faceId: i });
  58604. }
  58605. }
  58606. if (this._depthSort) {
  58607. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58608. }
  58609. return this._copy;
  58610. };
  58611. // returns a shape array from positions array
  58612. SolidParticleSystem.prototype._posToShape = function (positions) {
  58613. var shape = [];
  58614. for (var i = 0; i < positions.length; i += 3) {
  58615. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58616. }
  58617. return shape;
  58618. };
  58619. // returns a shapeUV array from a Vector4 uvs
  58620. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58621. var shapeUV = [];
  58622. if (uvs) {
  58623. for (var i = 0; i < uvs.length; i++)
  58624. shapeUV.push(uvs[i]);
  58625. }
  58626. return shapeUV;
  58627. };
  58628. // adds a new particle object in the particles array
  58629. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58630. if (bInfo === void 0) { bInfo = null; }
  58631. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58632. this.particles.push(sp);
  58633. return sp;
  58634. };
  58635. /**
  58636. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58637. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58638. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58639. * @param nb (positive integer) the number of particles to be created from this model
  58640. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58641. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58642. * @returns the number of shapes in the system
  58643. */
  58644. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58645. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58646. var meshInd = mesh.getIndices();
  58647. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58648. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58649. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58650. var bbInfo;
  58651. if (this._particlesIntersect) {
  58652. bbInfo = mesh.getBoundingInfo();
  58653. }
  58654. var shape = this._posToShape(meshPos);
  58655. var shapeUV = this._uvsToShapeUV(meshUV);
  58656. var posfunc = options ? options.positionFunction : null;
  58657. var vtxfunc = options ? options.vertexFunction : null;
  58658. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58659. // particles
  58660. var sp;
  58661. var currentCopy;
  58662. var idx = this.nbParticles;
  58663. for (var i = 0; i < nb; i++) {
  58664. var currentPos = this._positions.length;
  58665. var currentInd = this._indices.length;
  58666. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58667. if (this._updatable) {
  58668. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58669. sp.position.copyFrom(currentCopy.position);
  58670. sp.rotation.copyFrom(currentCopy.rotation);
  58671. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58672. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58673. }
  58674. if (currentCopy.color && sp.color) {
  58675. sp.color.copyFrom(currentCopy.color);
  58676. }
  58677. sp.scaling.copyFrom(currentCopy.scaling);
  58678. sp.uvs.copyFrom(currentCopy.uvs);
  58679. }
  58680. this._index += shape.length;
  58681. idx++;
  58682. }
  58683. this.nbParticles += nb;
  58684. this._shapeCounter++;
  58685. return this._shapeCounter - 1;
  58686. };
  58687. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58688. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58689. this._resetCopy();
  58690. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58691. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58692. }
  58693. if (this._copy.rotationQuaternion) {
  58694. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58695. }
  58696. else {
  58697. this._yaw = this._copy.rotation.y;
  58698. this._pitch = this._copy.rotation.x;
  58699. this._roll = this._copy.rotation.z;
  58700. this._quaternionRotationYPR();
  58701. }
  58702. this._quaternionToRotationMatrix();
  58703. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58704. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58705. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58706. if (this._copy.translateFromPivot) {
  58707. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58708. }
  58709. else {
  58710. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58711. }
  58712. this._shape = particle._model._shape;
  58713. for (var pt = 0; pt < this._shape.length; pt++) {
  58714. this._vertex.x = this._shape[pt].x;
  58715. this._vertex.y = this._shape[pt].y;
  58716. this._vertex.z = this._shape[pt].z;
  58717. if (particle._model._vertexFunction) {
  58718. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58719. }
  58720. this._vertex.x *= this._copy.scaling.x;
  58721. this._vertex.y *= this._copy.scaling.y;
  58722. this._vertex.z *= this._copy.scaling.z;
  58723. this._vertex.x -= this._scaledPivot.x;
  58724. this._vertex.y -= this._scaledPivot.y;
  58725. this._vertex.z -= this._scaledPivot.z;
  58726. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58727. this._rotated.addInPlace(this._pivotBackTranslation);
  58728. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58729. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58730. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58731. }
  58732. particle.position.x = 0.0;
  58733. particle.position.y = 0.0;
  58734. particle.position.z = 0.0;
  58735. particle.rotation.x = 0.0;
  58736. particle.rotation.y = 0.0;
  58737. particle.rotation.z = 0.0;
  58738. particle.rotationQuaternion = null;
  58739. particle.scaling.x = 1.0;
  58740. particle.scaling.y = 1.0;
  58741. particle.scaling.z = 1.0;
  58742. particle.uvs.x = 0.0;
  58743. particle.uvs.y = 0.0;
  58744. particle.uvs.z = 1.0;
  58745. particle.uvs.w = 1.0;
  58746. particle.pivot.x = 0.0;
  58747. particle.pivot.y = 0.0;
  58748. particle.pivot.z = 0.0;
  58749. particle.translateFromPivot = false;
  58750. particle.parentId = null;
  58751. };
  58752. /**
  58753. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58754. * @returns the SPS.
  58755. */
  58756. SolidParticleSystem.prototype.rebuildMesh = function () {
  58757. for (var p = 0; p < this.particles.length; p++) {
  58758. this._rebuildParticle(this.particles[p]);
  58759. }
  58760. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58761. return this;
  58762. };
  58763. /**
  58764. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58765. * This method calls `updateParticle()` for each particle of the SPS.
  58766. * For an animated SPS, it is usually called within the render loop.
  58767. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58768. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58769. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58770. * @returns the SPS.
  58771. */
  58772. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58773. if (start === void 0) { start = 0; }
  58774. if (end === void 0) { end = this.nbParticles - 1; }
  58775. if (update === void 0) { update = true; }
  58776. if (!this._updatable) {
  58777. return this;
  58778. }
  58779. // custom beforeUpdate
  58780. this.beforeUpdateParticles(start, end, update);
  58781. this._cam_axisX.x = 1.0;
  58782. this._cam_axisX.y = 0.0;
  58783. this._cam_axisX.z = 0.0;
  58784. this._cam_axisY.x = 0.0;
  58785. this._cam_axisY.y = 1.0;
  58786. this._cam_axisY.z = 0.0;
  58787. this._cam_axisZ.x = 0.0;
  58788. this._cam_axisZ.y = 0.0;
  58789. this._cam_axisZ.z = 1.0;
  58790. // cases when the World Matrix is to be computed first
  58791. if (this.billboard || this._depthSort) {
  58792. this.mesh.computeWorldMatrix(true);
  58793. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58794. }
  58795. // if the particles will always face the camera
  58796. if (this.billboard) {
  58797. // compute the camera position and un-rotate it by the current mesh rotation
  58798. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58799. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58800. this._cam_axisZ.normalize();
  58801. // same for camera up vector extracted from the cam view matrix
  58802. var view = this._camera.getViewMatrix(true);
  58803. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58804. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58805. this._cam_axisY.normalize();
  58806. this._cam_axisX.normalize();
  58807. }
  58808. // if depthSort, compute the camera global position in the mesh local system
  58809. if (this._depthSort) {
  58810. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58811. }
  58812. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58813. var idx = 0; // current position index in the global array positions32
  58814. var index = 0; // position start index in the global array positions32 of the current particle
  58815. var colidx = 0; // current color index in the global array colors32
  58816. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58817. var uvidx = 0; // current uv index in the global array uvs32
  58818. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58819. var pt = 0; // current index in the particle model shape
  58820. if (this.mesh.isFacetDataEnabled) {
  58821. this._computeBoundingBox = true;
  58822. }
  58823. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58824. if (this._computeBoundingBox) {
  58825. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58826. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58827. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58828. }
  58829. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58830. if (this.mesh._boundingInfo) {
  58831. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58832. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58833. }
  58834. }
  58835. }
  58836. // particle loop
  58837. index = this.particles[start]._pos;
  58838. var vpos = (index / 3) | 0;
  58839. colorIndex = vpos * 4;
  58840. uvIndex = vpos * 2;
  58841. for (var p = start; p <= end; p++) {
  58842. this._particle = this.particles[p];
  58843. this._shape = this._particle._model._shape;
  58844. this._shapeUV = this._particle._model._shapeUV;
  58845. // call to custom user function to update the particle properties
  58846. this.updateParticle(this._particle);
  58847. // camera-particle distance for depth sorting
  58848. if (this._depthSort && this._depthSortParticles) {
  58849. var dsp = this.depthSortedParticles[p];
  58850. dsp.ind = this._particle._ind;
  58851. dsp.indicesLength = this._particle._model._indicesLength;
  58852. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58853. }
  58854. // skip the computations for inactive or already invisible particles
  58855. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58856. // increment indexes for the next particle
  58857. pt = this._shape.length;
  58858. index += pt * 3;
  58859. colorIndex += pt * 4;
  58860. uvIndex += pt * 2;
  58861. continue;
  58862. }
  58863. if (this._particle.isVisible) {
  58864. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58865. this._particleHasParent = (this._particle.parentId !== null);
  58866. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58867. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58868. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58869. // particle rotation matrix
  58870. if (this.billboard) {
  58871. this._particle.rotation.x = 0.0;
  58872. this._particle.rotation.y = 0.0;
  58873. }
  58874. if (this._computeParticleRotation || this.billboard) {
  58875. if (this._particle.rotationQuaternion) {
  58876. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58877. }
  58878. else {
  58879. this._yaw = this._particle.rotation.y;
  58880. this._pitch = this._particle.rotation.x;
  58881. this._roll = this._particle.rotation.z;
  58882. this._quaternionRotationYPR();
  58883. }
  58884. this._quaternionToRotationMatrix();
  58885. }
  58886. if (this._particleHasParent) {
  58887. this._parent = this.particles[this._particle.parentId];
  58888. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  58889. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  58890. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  58891. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58892. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58893. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58894. if (this._computeParticleRotation || this.billboard) {
  58895. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  58896. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  58897. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  58898. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  58899. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  58900. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  58901. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  58902. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  58903. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  58904. }
  58905. }
  58906. else {
  58907. this._particle._globalPosition.x = this._particle.position.x;
  58908. this._particle._globalPosition.y = this._particle.position.y;
  58909. this._particle._globalPosition.z = this._particle.position.z;
  58910. if (this._computeParticleRotation || this.billboard) {
  58911. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58912. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58913. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58914. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58915. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58916. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58917. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58918. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58919. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58920. }
  58921. }
  58922. if (this._particle.translateFromPivot) {
  58923. this._pivotBackTranslation.x = 0.0;
  58924. this._pivotBackTranslation.y = 0.0;
  58925. this._pivotBackTranslation.z = 0.0;
  58926. }
  58927. else {
  58928. this._pivotBackTranslation.x = this._scaledPivot.x;
  58929. this._pivotBackTranslation.y = this._scaledPivot.y;
  58930. this._pivotBackTranslation.z = this._scaledPivot.z;
  58931. }
  58932. // particle vertex loop
  58933. for (pt = 0; pt < this._shape.length; pt++) {
  58934. idx = index + pt * 3;
  58935. colidx = colorIndex + pt * 4;
  58936. uvidx = uvIndex + pt * 2;
  58937. this._vertex.x = this._shape[pt].x;
  58938. this._vertex.y = this._shape[pt].y;
  58939. this._vertex.z = this._shape[pt].z;
  58940. if (this._computeParticleVertex) {
  58941. this.updateParticleVertex(this._particle, this._vertex, pt);
  58942. }
  58943. // positions
  58944. this._vertex.x *= this._particle.scaling.x;
  58945. this._vertex.y *= this._particle.scaling.y;
  58946. this._vertex.z *= this._particle.scaling.z;
  58947. this._vertex.x -= this._scaledPivot.x;
  58948. this._vertex.y -= this._scaledPivot.y;
  58949. this._vertex.z -= this._scaledPivot.z;
  58950. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58951. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58952. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58953. this._rotated.x += this._pivotBackTranslation.x;
  58954. this._rotated.y += this._pivotBackTranslation.y;
  58955. this._rotated.z += this._pivotBackTranslation.z;
  58956. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58957. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  58958. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  58959. if (this._computeBoundingBox) {
  58960. if (this._positions32[idx] < this._minimum.x) {
  58961. this._minimum.x = this._positions32[idx];
  58962. }
  58963. if (this._positions32[idx] > this._maximum.x) {
  58964. this._maximum.x = this._positions32[idx];
  58965. }
  58966. if (this._positions32[idx + 1] < this._minimum.y) {
  58967. this._minimum.y = this._positions32[idx + 1];
  58968. }
  58969. if (this._positions32[idx + 1] > this._maximum.y) {
  58970. this._maximum.y = this._positions32[idx + 1];
  58971. }
  58972. if (this._positions32[idx + 2] < this._minimum.z) {
  58973. this._minimum.z = this._positions32[idx + 2];
  58974. }
  58975. if (this._positions32[idx + 2] > this._maximum.z) {
  58976. this._maximum.z = this._positions32[idx + 2];
  58977. }
  58978. }
  58979. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58980. if (!this._computeParticleVertex) {
  58981. this._normal.x = this._fixedNormal32[idx];
  58982. this._normal.y = this._fixedNormal32[idx + 1];
  58983. this._normal.z = this._fixedNormal32[idx + 2];
  58984. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58985. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58986. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58987. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58988. 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;
  58989. 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;
  58990. }
  58991. if (this._computeParticleColor && this._particle.color) {
  58992. this._colors32[colidx] = this._particle.color.r;
  58993. this._colors32[colidx + 1] = this._particle.color.g;
  58994. this._colors32[colidx + 2] = this._particle.color.b;
  58995. this._colors32[colidx + 3] = this._particle.color.a;
  58996. }
  58997. if (this._computeParticleTexture) {
  58998. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58999. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59000. }
  59001. }
  59002. }
  59003. // particle just set invisible : scaled to zero and positioned at the origin
  59004. else {
  59005. this._particle._stillInvisible = true; // mark the particle as invisible
  59006. for (pt = 0; pt < this._shape.length; pt++) {
  59007. idx = index + pt * 3;
  59008. colidx = colorIndex + pt * 4;
  59009. uvidx = uvIndex + pt * 2;
  59010. this._positions32[idx] = 0.0;
  59011. this._positions32[idx + 1] = 0.0;
  59012. this._positions32[idx + 2] = 0.0;
  59013. this._normals32[idx] = 0.0;
  59014. this._normals32[idx + 1] = 0.0;
  59015. this._normals32[idx + 2] = 0.0;
  59016. if (this._computeParticleColor && this._particle.color) {
  59017. this._colors32[colidx] = this._particle.color.r;
  59018. this._colors32[colidx + 1] = this._particle.color.g;
  59019. this._colors32[colidx + 2] = this._particle.color.b;
  59020. this._colors32[colidx + 3] = this._particle.color.a;
  59021. }
  59022. if (this._computeParticleTexture) {
  59023. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59024. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59025. }
  59026. }
  59027. }
  59028. // if the particle intersections must be computed : update the bbInfo
  59029. if (this._particlesIntersect) {
  59030. var bInfo = this._particle._boundingInfo;
  59031. var bBox = bInfo.boundingBox;
  59032. var bSphere = bInfo.boundingSphere;
  59033. if (!this._bSphereOnly) {
  59034. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59035. for (var b = 0; b < bBox.vectors.length; b++) {
  59036. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59037. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59038. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59039. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59040. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59041. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59042. 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;
  59043. 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;
  59044. 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;
  59045. }
  59046. bBox._update(this.mesh._worldMatrix);
  59047. }
  59048. // place and scale the particle bouding sphere in the SPS local system, then update it
  59049. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59050. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59051. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59052. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59053. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59054. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59055. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59056. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59057. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59058. 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));
  59059. bSphere._update(this.mesh._worldMatrix);
  59060. }
  59061. // increment indexes for the next particle
  59062. index = idx + 3;
  59063. colorIndex = colidx + 4;
  59064. uvIndex = uvidx + 2;
  59065. }
  59066. // if the VBO must be updated
  59067. if (update) {
  59068. if (this._computeParticleColor) {
  59069. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59070. }
  59071. if (this._computeParticleTexture) {
  59072. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59073. }
  59074. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59075. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59076. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59077. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59078. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59079. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59080. for (var i = 0; i < this._normals32.length; i++) {
  59081. this._fixedNormal32[i] = this._normals32[i];
  59082. }
  59083. }
  59084. if (!this.mesh.areNormalsFrozen) {
  59085. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59086. }
  59087. }
  59088. if (this._depthSort && this._depthSortParticles) {
  59089. this.depthSortedParticles.sort(this._depthSortFunction);
  59090. var dspl = this.depthSortedParticles.length;
  59091. var sorted = 0;
  59092. var lind = 0;
  59093. var sind = 0;
  59094. var sid = 0;
  59095. for (sorted = 0; sorted < dspl; sorted++) {
  59096. lind = this.depthSortedParticles[sorted].indicesLength;
  59097. sind = this.depthSortedParticles[sorted].ind;
  59098. for (var i = 0; i < lind; i++) {
  59099. this._indices32[sid] = this._indices[sind + i];
  59100. sid++;
  59101. }
  59102. }
  59103. this.mesh.updateIndices(this._indices32);
  59104. }
  59105. }
  59106. if (this._computeBoundingBox) {
  59107. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59108. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59109. }
  59110. this.afterUpdateParticles(start, end, update);
  59111. return this;
  59112. };
  59113. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59114. this._halfroll = this._roll * 0.5;
  59115. this._halfpitch = this._pitch * 0.5;
  59116. this._halfyaw = this._yaw * 0.5;
  59117. this._sinRoll = Math.sin(this._halfroll);
  59118. this._cosRoll = Math.cos(this._halfroll);
  59119. this._sinPitch = Math.sin(this._halfpitch);
  59120. this._cosPitch = Math.cos(this._halfpitch);
  59121. this._sinYaw = Math.sin(this._halfyaw);
  59122. this._cosYaw = Math.cos(this._halfyaw);
  59123. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59124. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59125. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59126. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59127. };
  59128. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59129. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59130. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59131. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59132. this._rotMatrix.m[3] = 0;
  59133. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59134. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59135. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59136. this._rotMatrix.m[7] = 0;
  59137. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59138. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59139. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59140. this._rotMatrix.m[11] = 0;
  59141. this._rotMatrix.m[12] = 0;
  59142. this._rotMatrix.m[13] = 0;
  59143. this._rotMatrix.m[14] = 0;
  59144. this._rotMatrix.m[15] = 1.0;
  59145. };
  59146. /**
  59147. * Disposes the SPS.
  59148. */
  59149. SolidParticleSystem.prototype.dispose = function () {
  59150. this.mesh.dispose();
  59151. this.vars = null;
  59152. // drop references to internal big arrays for the GC
  59153. this._positions = null;
  59154. this._indices = null;
  59155. this._normals = null;
  59156. this._uvs = null;
  59157. this._colors = null;
  59158. this._indices32 = null;
  59159. this._positions32 = null;
  59160. this._normals32 = null;
  59161. this._fixedNormal32 = null;
  59162. this._uvs32 = null;
  59163. this._colors32 = null;
  59164. this.pickedParticles = null;
  59165. };
  59166. /**
  59167. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59168. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59169. * @returns the SPS.
  59170. */
  59171. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59172. if (!this._isVisibilityBoxLocked) {
  59173. this.mesh.refreshBoundingInfo();
  59174. }
  59175. return this;
  59176. };
  59177. /**
  59178. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59179. * @param size the size (float) of the visibility box
  59180. * note : this doesn't lock the SPS mesh bounding box.
  59181. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59182. */
  59183. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59184. var vis = size / 2;
  59185. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59186. };
  59187. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59188. /**
  59189. * Gets whether the SPS as always visible or not
  59190. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59191. */
  59192. get: function () {
  59193. return this._alwaysVisible;
  59194. },
  59195. /**
  59196. * Sets the SPS as always visible or not
  59197. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59198. */
  59199. set: function (val) {
  59200. this._alwaysVisible = val;
  59201. this.mesh.alwaysSelectAsActiveMesh = val;
  59202. },
  59203. enumerable: true,
  59204. configurable: true
  59205. });
  59206. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59207. /**
  59208. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59209. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59210. */
  59211. get: function () {
  59212. return this._isVisibilityBoxLocked;
  59213. },
  59214. /**
  59215. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59216. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59217. */
  59218. set: function (val) {
  59219. this._isVisibilityBoxLocked = val;
  59220. var boundingInfo = this.mesh.getBoundingInfo();
  59221. boundingInfo.isLocked = val;
  59222. },
  59223. enumerable: true,
  59224. configurable: true
  59225. });
  59226. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59227. /**
  59228. * Gets if `setParticles()` computes the particle rotations or not.
  59229. * Default value : true. The SPS is faster when it's set to false.
  59230. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59231. */
  59232. get: function () {
  59233. return this._computeParticleRotation;
  59234. },
  59235. /**
  59236. * Tells to `setParticles()` to compute the particle rotations or not.
  59237. * Default value : true. The SPS is faster when it's set to false.
  59238. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59239. */
  59240. set: function (val) {
  59241. this._computeParticleRotation = val;
  59242. },
  59243. enumerable: true,
  59244. configurable: true
  59245. });
  59246. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59247. /**
  59248. * Gets if `setParticles()` computes the particle colors or not.
  59249. * Default value : true. The SPS is faster when it's set to false.
  59250. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59251. */
  59252. get: function () {
  59253. return this._computeParticleColor;
  59254. },
  59255. /**
  59256. * Tells to `setParticles()` to compute the particle colors or not.
  59257. * Default value : true. The SPS is faster when it's set to false.
  59258. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59259. */
  59260. set: function (val) {
  59261. this._computeParticleColor = val;
  59262. },
  59263. enumerable: true,
  59264. configurable: true
  59265. });
  59266. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59267. /**
  59268. * Gets if `setParticles()` computes the particle textures or not.
  59269. * Default value : true. The SPS is faster when it's set to false.
  59270. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59271. */
  59272. get: function () {
  59273. return this._computeParticleTexture;
  59274. },
  59275. set: function (val) {
  59276. this._computeParticleTexture = val;
  59277. },
  59278. enumerable: true,
  59279. configurable: true
  59280. });
  59281. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59282. /**
  59283. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59284. * Default value : false. The SPS is faster when it's set to false.
  59285. * Note : the particle custom vertex positions aren't stored values.
  59286. */
  59287. get: function () {
  59288. return this._computeParticleVertex;
  59289. },
  59290. /**
  59291. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59292. * Default value : false. The SPS is faster when it's set to false.
  59293. * Note : the particle custom vertex positions aren't stored values.
  59294. */
  59295. set: function (val) {
  59296. this._computeParticleVertex = val;
  59297. },
  59298. enumerable: true,
  59299. configurable: true
  59300. });
  59301. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59302. /**
  59303. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59304. */
  59305. get: function () {
  59306. return this._computeBoundingBox;
  59307. },
  59308. /**
  59309. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59310. */
  59311. set: function (val) {
  59312. this._computeBoundingBox = val;
  59313. },
  59314. enumerable: true,
  59315. configurable: true
  59316. });
  59317. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59318. /**
  59319. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59320. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59321. * Default : `true`
  59322. */
  59323. get: function () {
  59324. return this._depthSortParticles;
  59325. },
  59326. /**
  59327. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59328. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59329. * Default : `true`
  59330. */
  59331. set: function (val) {
  59332. this._depthSortParticles = val;
  59333. },
  59334. enumerable: true,
  59335. configurable: true
  59336. });
  59337. // =======================================================================
  59338. // Particle behavior logic
  59339. // these following methods may be overwritten by the user to fit his needs
  59340. /**
  59341. * This function does nothing. It may be overwritten to set all the particle first values.
  59342. * The SPS doesn't call this function, you may have to call it by your own.
  59343. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59344. */
  59345. SolidParticleSystem.prototype.initParticles = function () {
  59346. };
  59347. /**
  59348. * This function does nothing. It may be overwritten to recycle a particle.
  59349. * The SPS doesn't call this function, you may have to call it by your own.
  59350. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59351. * @param particle The particle to recycle
  59352. * @returns the recycled particle
  59353. */
  59354. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59355. return particle;
  59356. };
  59357. /**
  59358. * Updates a particle : this function should be overwritten by the user.
  59359. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59360. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59361. * @example : just set a particle position or velocity and recycle conditions
  59362. * @param particle The particle to update
  59363. * @returns the updated particle
  59364. */
  59365. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59366. return particle;
  59367. };
  59368. /**
  59369. * Updates a vertex of a particle : it can be overwritten by the user.
  59370. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59371. * @param particle the current particle
  59372. * @param vertex the current index of the current particle
  59373. * @param pt the index of the current vertex in the particle shape
  59374. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59375. * @example : just set a vertex particle position
  59376. * @returns the updated vertex
  59377. */
  59378. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59379. return vertex;
  59380. };
  59381. /**
  59382. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59383. * This does nothing and may be overwritten by the user.
  59384. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59385. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59386. * @param update the boolean update value actually passed to setParticles()
  59387. */
  59388. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59389. };
  59390. /**
  59391. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59392. * This will be passed three parameters.
  59393. * This does nothing and may be overwritten by the user.
  59394. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59395. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59396. * @param update the boolean update value actually passed to setParticles()
  59397. */
  59398. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59399. };
  59400. return SolidParticleSystem;
  59401. }());
  59402. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59403. })(BABYLON || (BABYLON = {}));
  59404. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59405. var BABYLON;
  59406. (function (BABYLON) {
  59407. var ShaderMaterial = /** @class */ (function (_super) {
  59408. __extends(ShaderMaterial, _super);
  59409. function ShaderMaterial(name, scene, shaderPath, options) {
  59410. var _this = _super.call(this, name, scene) || this;
  59411. _this._textures = {};
  59412. _this._textureArrays = {};
  59413. _this._floats = {};
  59414. _this._ints = {};
  59415. _this._floatsArrays = {};
  59416. _this._colors3 = {};
  59417. _this._colors3Arrays = {};
  59418. _this._colors4 = {};
  59419. _this._vectors2 = {};
  59420. _this._vectors3 = {};
  59421. _this._vectors4 = {};
  59422. _this._matrices = {};
  59423. _this._matrices3x3 = {};
  59424. _this._matrices2x2 = {};
  59425. _this._vectors2Arrays = {};
  59426. _this._vectors3Arrays = {};
  59427. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59428. _this._shaderPath = shaderPath;
  59429. options.needAlphaBlending = options.needAlphaBlending || false;
  59430. options.needAlphaTesting = options.needAlphaTesting || false;
  59431. options.attributes = options.attributes || ["position", "normal", "uv"];
  59432. options.uniforms = options.uniforms || ["worldViewProjection"];
  59433. options.uniformBuffers = options.uniformBuffers || [];
  59434. options.samplers = options.samplers || [];
  59435. options.defines = options.defines || [];
  59436. _this._options = options;
  59437. return _this;
  59438. }
  59439. ShaderMaterial.prototype.getClassName = function () {
  59440. return "ShaderMaterial";
  59441. };
  59442. ShaderMaterial.prototype.needAlphaBlending = function () {
  59443. return this._options.needAlphaBlending;
  59444. };
  59445. ShaderMaterial.prototype.needAlphaTesting = function () {
  59446. return this._options.needAlphaTesting;
  59447. };
  59448. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59449. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59450. this._options.uniforms.push(uniformName);
  59451. }
  59452. };
  59453. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59454. if (this._options.samplers.indexOf(name) === -1) {
  59455. this._options.samplers.push(name);
  59456. }
  59457. this._textures[name] = texture;
  59458. return this;
  59459. };
  59460. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59461. if (this._options.samplers.indexOf(name) === -1) {
  59462. this._options.samplers.push(name);
  59463. }
  59464. this._checkUniform(name);
  59465. this._textureArrays[name] = textures;
  59466. return this;
  59467. };
  59468. ShaderMaterial.prototype.setFloat = function (name, value) {
  59469. this._checkUniform(name);
  59470. this._floats[name] = value;
  59471. return this;
  59472. };
  59473. ShaderMaterial.prototype.setInt = function (name, value) {
  59474. this._checkUniform(name);
  59475. this._ints[name] = value;
  59476. return this;
  59477. };
  59478. ShaderMaterial.prototype.setFloats = function (name, value) {
  59479. this._checkUniform(name);
  59480. this._floatsArrays[name] = value;
  59481. return this;
  59482. };
  59483. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59484. this._checkUniform(name);
  59485. this._colors3[name] = value;
  59486. return this;
  59487. };
  59488. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59489. this._checkUniform(name);
  59490. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59491. color.toArray(arr, arr.length);
  59492. return arr;
  59493. }, []);
  59494. return this;
  59495. };
  59496. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59497. this._checkUniform(name);
  59498. this._colors4[name] = value;
  59499. return this;
  59500. };
  59501. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59502. this._checkUniform(name);
  59503. this._vectors2[name] = value;
  59504. return this;
  59505. };
  59506. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59507. this._checkUniform(name);
  59508. this._vectors3[name] = value;
  59509. return this;
  59510. };
  59511. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59512. this._checkUniform(name);
  59513. this._vectors4[name] = value;
  59514. return this;
  59515. };
  59516. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59517. this._checkUniform(name);
  59518. this._matrices[name] = value;
  59519. return this;
  59520. };
  59521. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59522. this._checkUniform(name);
  59523. this._matrices3x3[name] = value;
  59524. return this;
  59525. };
  59526. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59527. this._checkUniform(name);
  59528. this._matrices2x2[name] = value;
  59529. return this;
  59530. };
  59531. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59532. this._checkUniform(name);
  59533. this._vectors2Arrays[name] = value;
  59534. return this;
  59535. };
  59536. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59537. this._checkUniform(name);
  59538. this._vectors3Arrays[name] = value;
  59539. return this;
  59540. };
  59541. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59542. if (!mesh) {
  59543. return true;
  59544. }
  59545. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59546. return false;
  59547. }
  59548. return false;
  59549. };
  59550. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59551. var scene = this.getScene();
  59552. var engine = scene.getEngine();
  59553. if (!this.checkReadyOnEveryCall) {
  59554. if (this._renderId === scene.getRenderId()) {
  59555. if (this._checkCache(scene, mesh, useInstances)) {
  59556. return true;
  59557. }
  59558. }
  59559. }
  59560. // Instances
  59561. var defines = [];
  59562. var attribs = [];
  59563. var fallbacks = new BABYLON.EffectFallbacks();
  59564. if (useInstances) {
  59565. defines.push("#define INSTANCES");
  59566. }
  59567. for (var index = 0; index < this._options.defines.length; index++) {
  59568. defines.push(this._options.defines[index]);
  59569. }
  59570. for (var index = 0; index < this._options.attributes.length; index++) {
  59571. attribs.push(this._options.attributes[index]);
  59572. }
  59573. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59574. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59575. defines.push("#define VERTEXCOLOR");
  59576. }
  59577. // Bones
  59578. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59579. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59580. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59581. if (mesh.numBoneInfluencers > 4) {
  59582. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59583. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59584. }
  59585. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59586. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59587. fallbacks.addCPUSkinningFallback(0, mesh);
  59588. if (this._options.uniforms.indexOf("mBones") === -1) {
  59589. this._options.uniforms.push("mBones");
  59590. }
  59591. }
  59592. else {
  59593. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59594. }
  59595. // Textures
  59596. for (var name in this._textures) {
  59597. if (!this._textures[name].isReady()) {
  59598. return false;
  59599. }
  59600. }
  59601. // Alpha test
  59602. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59603. defines.push("#define ALPHATEST");
  59604. }
  59605. var previousEffect = this._effect;
  59606. var join = defines.join("\n");
  59607. this._effect = engine.createEffect(this._shaderPath, {
  59608. attributes: attribs,
  59609. uniformsNames: this._options.uniforms,
  59610. uniformBuffersNames: this._options.uniformBuffers,
  59611. samplers: this._options.samplers,
  59612. defines: join,
  59613. fallbacks: fallbacks,
  59614. onCompiled: this.onCompiled,
  59615. onError: this.onError
  59616. }, engine);
  59617. if (!this._effect.isReady()) {
  59618. return false;
  59619. }
  59620. if (previousEffect !== this._effect) {
  59621. scene.resetCachedMaterial();
  59622. }
  59623. this._renderId = scene.getRenderId();
  59624. return true;
  59625. };
  59626. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59627. var scene = this.getScene();
  59628. if (!this._effect) {
  59629. return;
  59630. }
  59631. if (this._options.uniforms.indexOf("world") !== -1) {
  59632. this._effect.setMatrix("world", world);
  59633. }
  59634. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59635. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59636. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59637. }
  59638. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59639. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59640. }
  59641. };
  59642. ShaderMaterial.prototype.bind = function (world, mesh) {
  59643. // Std values
  59644. this.bindOnlyWorldMatrix(world);
  59645. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59646. if (this._options.uniforms.indexOf("view") !== -1) {
  59647. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59648. }
  59649. if (this._options.uniforms.indexOf("projection") !== -1) {
  59650. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59651. }
  59652. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59653. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59654. }
  59655. // Bones
  59656. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59657. var name;
  59658. // Texture
  59659. for (name in this._textures) {
  59660. this._effect.setTexture(name, this._textures[name]);
  59661. }
  59662. // Texture arrays
  59663. for (name in this._textureArrays) {
  59664. this._effect.setTextureArray(name, this._textureArrays[name]);
  59665. }
  59666. // Int
  59667. for (name in this._ints) {
  59668. this._effect.setInt(name, this._ints[name]);
  59669. }
  59670. // Float
  59671. for (name in this._floats) {
  59672. this._effect.setFloat(name, this._floats[name]);
  59673. }
  59674. // Floats
  59675. for (name in this._floatsArrays) {
  59676. this._effect.setArray(name, this._floatsArrays[name]);
  59677. }
  59678. // Color3
  59679. for (name in this._colors3) {
  59680. this._effect.setColor3(name, this._colors3[name]);
  59681. }
  59682. for (name in this._colors3Arrays) {
  59683. this._effect.setArray3(name, this._colors3Arrays[name]);
  59684. }
  59685. // Color4
  59686. for (name in this._colors4) {
  59687. var color = this._colors4[name];
  59688. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59689. }
  59690. // Vector2
  59691. for (name in this._vectors2) {
  59692. this._effect.setVector2(name, this._vectors2[name]);
  59693. }
  59694. // Vector3
  59695. for (name in this._vectors3) {
  59696. this._effect.setVector3(name, this._vectors3[name]);
  59697. }
  59698. // Vector4
  59699. for (name in this._vectors4) {
  59700. this._effect.setVector4(name, this._vectors4[name]);
  59701. }
  59702. // Matrix
  59703. for (name in this._matrices) {
  59704. this._effect.setMatrix(name, this._matrices[name]);
  59705. }
  59706. // Matrix 3x3
  59707. for (name in this._matrices3x3) {
  59708. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59709. }
  59710. // Matrix 2x2
  59711. for (name in this._matrices2x2) {
  59712. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59713. }
  59714. // Vector2Array
  59715. for (name in this._vectors2Arrays) {
  59716. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59717. }
  59718. // Vector3Array
  59719. for (name in this._vectors3Arrays) {
  59720. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59721. }
  59722. }
  59723. this._afterBind(mesh);
  59724. };
  59725. ShaderMaterial.prototype.getActiveTextures = function () {
  59726. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59727. for (var name in this._textures) {
  59728. activeTextures.push(this._textures[name]);
  59729. }
  59730. for (var name in this._textureArrays) {
  59731. var array = this._textureArrays[name];
  59732. for (var index = 0; index < array.length; index++) {
  59733. activeTextures.push(array[index]);
  59734. }
  59735. }
  59736. return activeTextures;
  59737. };
  59738. ShaderMaterial.prototype.hasTexture = function (texture) {
  59739. if (_super.prototype.hasTexture.call(this, texture)) {
  59740. return true;
  59741. }
  59742. for (var name in this._textures) {
  59743. if (this._textures[name] === texture) {
  59744. return true;
  59745. }
  59746. }
  59747. for (var name in this._textureArrays) {
  59748. var array = this._textureArrays[name];
  59749. for (var index = 0; index < array.length; index++) {
  59750. if (array[index] === texture) {
  59751. return true;
  59752. }
  59753. }
  59754. }
  59755. return false;
  59756. };
  59757. ShaderMaterial.prototype.clone = function (name) {
  59758. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59759. return newShaderMaterial;
  59760. };
  59761. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59762. if (forceDisposeTextures) {
  59763. var name;
  59764. for (name in this._textures) {
  59765. this._textures[name].dispose();
  59766. }
  59767. for (name in this._textureArrays) {
  59768. var array = this._textureArrays[name];
  59769. for (var index = 0; index < array.length; index++) {
  59770. array[index].dispose();
  59771. }
  59772. }
  59773. }
  59774. this._textures = {};
  59775. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59776. };
  59777. ShaderMaterial.prototype.serialize = function () {
  59778. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59779. serializationObject.customType = "BABYLON.ShaderMaterial";
  59780. serializationObject.options = this._options;
  59781. serializationObject.shaderPath = this._shaderPath;
  59782. var name;
  59783. // Texture
  59784. serializationObject.textures = {};
  59785. for (name in this._textures) {
  59786. serializationObject.textures[name] = this._textures[name].serialize();
  59787. }
  59788. // Texture arrays
  59789. serializationObject.textureArrays = {};
  59790. for (name in this._textureArrays) {
  59791. serializationObject.textureArrays[name] = [];
  59792. var array = this._textureArrays[name];
  59793. for (var index = 0; index < array.length; index++) {
  59794. serializationObject.textureArrays[name].push(array[index].serialize());
  59795. }
  59796. }
  59797. // Float
  59798. serializationObject.floats = {};
  59799. for (name in this._floats) {
  59800. serializationObject.floats[name] = this._floats[name];
  59801. }
  59802. // Float s
  59803. serializationObject.FloatArrays = {};
  59804. for (name in this._floatsArrays) {
  59805. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59806. }
  59807. // Color3
  59808. serializationObject.colors3 = {};
  59809. for (name in this._colors3) {
  59810. serializationObject.colors3[name] = this._colors3[name].asArray();
  59811. }
  59812. // Color3 array
  59813. serializationObject.colors3Arrays = {};
  59814. for (name in this._colors3Arrays) {
  59815. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59816. }
  59817. // Color4
  59818. serializationObject.colors4 = {};
  59819. for (name in this._colors4) {
  59820. serializationObject.colors4[name] = this._colors4[name].asArray();
  59821. }
  59822. // Vector2
  59823. serializationObject.vectors2 = {};
  59824. for (name in this._vectors2) {
  59825. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59826. }
  59827. // Vector3
  59828. serializationObject.vectors3 = {};
  59829. for (name in this._vectors3) {
  59830. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59831. }
  59832. // Vector4
  59833. serializationObject.vectors4 = {};
  59834. for (name in this._vectors4) {
  59835. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59836. }
  59837. // Matrix
  59838. serializationObject.matrices = {};
  59839. for (name in this._matrices) {
  59840. serializationObject.matrices[name] = this._matrices[name].asArray();
  59841. }
  59842. // Matrix 3x3
  59843. serializationObject.matrices3x3 = {};
  59844. for (name in this._matrices3x3) {
  59845. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59846. }
  59847. // Matrix 2x2
  59848. serializationObject.matrices2x2 = {};
  59849. for (name in this._matrices2x2) {
  59850. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59851. }
  59852. // Vector2Array
  59853. serializationObject.vectors2Arrays = {};
  59854. for (name in this._vectors2Arrays) {
  59855. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59856. }
  59857. // Vector3Array
  59858. serializationObject.vectors3Arrays = {};
  59859. for (name in this._vectors3Arrays) {
  59860. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59861. }
  59862. return serializationObject;
  59863. };
  59864. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59865. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59866. var name;
  59867. // Texture
  59868. for (name in source.textures) {
  59869. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59870. }
  59871. // Texture arrays
  59872. for (name in source.textureArrays) {
  59873. var array = source.textureArrays[name];
  59874. var textureArray = new Array();
  59875. for (var index = 0; index < array.length; index++) {
  59876. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59877. }
  59878. material.setTextureArray(name, textureArray);
  59879. }
  59880. // Float
  59881. for (name in source.floats) {
  59882. material.setFloat(name, source.floats[name]);
  59883. }
  59884. // Float s
  59885. for (name in source.floatsArrays) {
  59886. material.setFloats(name, source.floatsArrays[name]);
  59887. }
  59888. // Color3
  59889. for (name in source.colors3) {
  59890. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59891. }
  59892. // Color3 arrays
  59893. for (name in source.colors3Arrays) {
  59894. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59895. if (i % 3 === 0) {
  59896. arr.push([num]);
  59897. }
  59898. else {
  59899. arr[arr.length - 1].push(num);
  59900. }
  59901. return arr;
  59902. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59903. material.setColor3Array(name, colors);
  59904. }
  59905. // Color4
  59906. for (name in source.colors4) {
  59907. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59908. }
  59909. // Vector2
  59910. for (name in source.vectors2) {
  59911. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59912. }
  59913. // Vector3
  59914. for (name in source.vectors3) {
  59915. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59916. }
  59917. // Vector4
  59918. for (name in source.vectors4) {
  59919. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59920. }
  59921. // Matrix
  59922. for (name in source.matrices) {
  59923. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59924. }
  59925. // Matrix 3x3
  59926. for (name in source.matrices3x3) {
  59927. material.setMatrix3x3(name, source.matrices3x3[name]);
  59928. }
  59929. // Matrix 2x2
  59930. for (name in source.matrices2x2) {
  59931. material.setMatrix2x2(name, source.matrices2x2[name]);
  59932. }
  59933. // Vector2Array
  59934. for (name in source.vectors2Arrays) {
  59935. material.setArray2(name, source.vectors2Arrays[name]);
  59936. }
  59937. // Vector3Array
  59938. for (name in source.vectors3Arrays) {
  59939. material.setArray3(name, source.vectors3Arrays[name]);
  59940. }
  59941. return material;
  59942. };
  59943. return ShaderMaterial;
  59944. }(BABYLON.Material));
  59945. BABYLON.ShaderMaterial = ShaderMaterial;
  59946. })(BABYLON || (BABYLON = {}));
  59947. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59948. var BABYLON;
  59949. (function (BABYLON) {
  59950. var GroundMesh = /** @class */ (function (_super) {
  59951. __extends(GroundMesh, _super);
  59952. function GroundMesh(name, scene) {
  59953. var _this = _super.call(this, name, scene) || this;
  59954. _this.generateOctree = false;
  59955. return _this;
  59956. }
  59957. GroundMesh.prototype.getClassName = function () {
  59958. return "GroundMesh";
  59959. };
  59960. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59961. get: function () {
  59962. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59963. },
  59964. enumerable: true,
  59965. configurable: true
  59966. });
  59967. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59968. get: function () {
  59969. return this._subdivisionsX;
  59970. },
  59971. enumerable: true,
  59972. configurable: true
  59973. });
  59974. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59975. get: function () {
  59976. return this._subdivisionsY;
  59977. },
  59978. enumerable: true,
  59979. configurable: true
  59980. });
  59981. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59982. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59983. this._subdivisionsX = chunksCount;
  59984. this._subdivisionsY = chunksCount;
  59985. this.subdivide(chunksCount);
  59986. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59987. };
  59988. /**
  59989. * Returns a height (y) value in the Worl system :
  59990. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59991. * Returns the ground y position if (x, z) are outside the ground surface.
  59992. */
  59993. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59994. var world = this.getWorldMatrix();
  59995. var invMat = BABYLON.Tmp.Matrix[5];
  59996. world.invertToRef(invMat);
  59997. var tmpVect = BABYLON.Tmp.Vector3[8];
  59998. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59999. x = tmpVect.x;
  60000. z = tmpVect.z;
  60001. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60002. return this.position.y;
  60003. }
  60004. if (!this._heightQuads || this._heightQuads.length == 0) {
  60005. this._initHeightQuads();
  60006. this._computeHeightQuads();
  60007. }
  60008. var facet = this._getFacetAt(x, z);
  60009. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60010. // return y in the World system
  60011. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60012. return tmpVect.y;
  60013. };
  60014. /**
  60015. * Returns a normalized vector (Vector3) orthogonal to the ground
  60016. * at the ground coordinates (x, z) expressed in the World system.
  60017. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60018. */
  60019. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60020. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60021. this.getNormalAtCoordinatesToRef(x, z, normal);
  60022. return normal;
  60023. };
  60024. /**
  60025. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60026. * at the ground coordinates (x, z) expressed in the World system.
  60027. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60028. * Returns the GroundMesh.
  60029. */
  60030. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60031. var world = this.getWorldMatrix();
  60032. var tmpMat = BABYLON.Tmp.Matrix[5];
  60033. world.invertToRef(tmpMat);
  60034. var tmpVect = BABYLON.Tmp.Vector3[8];
  60035. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60036. x = tmpVect.x;
  60037. z = tmpVect.z;
  60038. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60039. return this;
  60040. }
  60041. if (!this._heightQuads || this._heightQuads.length == 0) {
  60042. this._initHeightQuads();
  60043. this._computeHeightQuads();
  60044. }
  60045. var facet = this._getFacetAt(x, z);
  60046. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60047. return this;
  60048. };
  60049. /**
  60050. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60051. * if the ground has been updated.
  60052. * This can be used in the render loop.
  60053. * Returns the GroundMesh.
  60054. */
  60055. GroundMesh.prototype.updateCoordinateHeights = function () {
  60056. if (!this._heightQuads || this._heightQuads.length == 0) {
  60057. this._initHeightQuads();
  60058. }
  60059. this._computeHeightQuads();
  60060. return this;
  60061. };
  60062. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60063. GroundMesh.prototype._getFacetAt = function (x, z) {
  60064. // retrieve col and row from x, z coordinates in the ground local system
  60065. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60066. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60067. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60068. var facet;
  60069. if (z < quad.slope.x * x + quad.slope.y) {
  60070. facet = quad.facet1;
  60071. }
  60072. else {
  60073. facet = quad.facet2;
  60074. }
  60075. return facet;
  60076. };
  60077. // Creates and populates the heightMap array with "facet" elements :
  60078. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60079. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60080. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60081. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60082. // Returns the GroundMesh.
  60083. GroundMesh.prototype._initHeightQuads = function () {
  60084. var subdivisionsX = this._subdivisionsX;
  60085. var subdivisionsY = this._subdivisionsY;
  60086. this._heightQuads = new Array();
  60087. for (var row = 0; row < subdivisionsY; row++) {
  60088. for (var col = 0; col < subdivisionsX; col++) {
  60089. 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) };
  60090. this._heightQuads[row * subdivisionsX + col] = quad;
  60091. }
  60092. }
  60093. return this;
  60094. };
  60095. // Compute each quad element values and update the the heightMap array :
  60096. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60097. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60098. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60099. // Returns the GroundMesh.
  60100. GroundMesh.prototype._computeHeightQuads = function () {
  60101. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60102. if (!positions) {
  60103. return this;
  60104. }
  60105. var v1 = BABYLON.Tmp.Vector3[3];
  60106. var v2 = BABYLON.Tmp.Vector3[2];
  60107. var v3 = BABYLON.Tmp.Vector3[1];
  60108. var v4 = BABYLON.Tmp.Vector3[0];
  60109. var v1v2 = BABYLON.Tmp.Vector3[4];
  60110. var v1v3 = BABYLON.Tmp.Vector3[5];
  60111. var v1v4 = BABYLON.Tmp.Vector3[6];
  60112. var norm1 = BABYLON.Tmp.Vector3[7];
  60113. var norm2 = BABYLON.Tmp.Vector3[8];
  60114. var i = 0;
  60115. var j = 0;
  60116. var k = 0;
  60117. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60118. var h = 0;
  60119. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60120. var d2 = 0;
  60121. var subdivisionsX = this._subdivisionsX;
  60122. var subdivisionsY = this._subdivisionsY;
  60123. for (var row = 0; row < subdivisionsY; row++) {
  60124. for (var col = 0; col < subdivisionsX; col++) {
  60125. i = col * 3;
  60126. j = row * (subdivisionsX + 1) * 3;
  60127. k = (row + 1) * (subdivisionsX + 1) * 3;
  60128. v1.x = positions[j + i];
  60129. v1.y = positions[j + i + 1];
  60130. v1.z = positions[j + i + 2];
  60131. v2.x = positions[j + i + 3];
  60132. v2.y = positions[j + i + 4];
  60133. v2.z = positions[j + i + 5];
  60134. v3.x = positions[k + i];
  60135. v3.y = positions[k + i + 1];
  60136. v3.z = positions[k + i + 2];
  60137. v4.x = positions[k + i + 3];
  60138. v4.y = positions[k + i + 4];
  60139. v4.z = positions[k + i + 5];
  60140. // 2D slope V1V4
  60141. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60142. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60143. // facet equations :
  60144. // we compute each facet normal vector
  60145. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60146. // we compute the value d by applying the equation to v1 which belongs to the plane
  60147. // then we store the facet equation in a Vector4
  60148. v2.subtractToRef(v1, v1v2);
  60149. v3.subtractToRef(v1, v1v3);
  60150. v4.subtractToRef(v1, v1v4);
  60151. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60152. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60153. norm1.normalize();
  60154. norm2.normalize();
  60155. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60156. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60157. var quad = this._heightQuads[row * subdivisionsX + col];
  60158. quad.slope.copyFromFloats(cd, h);
  60159. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60160. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60161. }
  60162. }
  60163. return this;
  60164. };
  60165. GroundMesh.prototype.serialize = function (serializationObject) {
  60166. _super.prototype.serialize.call(this, serializationObject);
  60167. serializationObject.subdivisionsX = this._subdivisionsX;
  60168. serializationObject.subdivisionsY = this._subdivisionsY;
  60169. serializationObject.minX = this._minX;
  60170. serializationObject.maxX = this._maxX;
  60171. serializationObject.minZ = this._minZ;
  60172. serializationObject.maxZ = this._maxZ;
  60173. serializationObject.width = this._width;
  60174. serializationObject.height = this._height;
  60175. };
  60176. GroundMesh.Parse = function (parsedMesh, scene) {
  60177. var result = new GroundMesh(parsedMesh.name, scene);
  60178. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60179. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60180. result._minX = parsedMesh.minX;
  60181. result._maxX = parsedMesh.maxX;
  60182. result._minZ = parsedMesh.minZ;
  60183. result._maxZ = parsedMesh.maxZ;
  60184. result._width = parsedMesh.width;
  60185. result._height = parsedMesh.height;
  60186. return result;
  60187. };
  60188. return GroundMesh;
  60189. }(BABYLON.Mesh));
  60190. BABYLON.GroundMesh = GroundMesh;
  60191. })(BABYLON || (BABYLON = {}));
  60192. //# sourceMappingURL=babylon.groundMesh.js.map
  60193. var BABYLON;
  60194. (function (BABYLON) {
  60195. /**
  60196. * Creates an instance based on a source mesh.
  60197. */
  60198. var InstancedMesh = /** @class */ (function (_super) {
  60199. __extends(InstancedMesh, _super);
  60200. function InstancedMesh(name, source) {
  60201. var _this = _super.call(this, name, source.getScene()) || this;
  60202. source.instances.push(_this);
  60203. _this._sourceMesh = source;
  60204. _this.position.copyFrom(source.position);
  60205. _this.rotation.copyFrom(source.rotation);
  60206. _this.scaling.copyFrom(source.scaling);
  60207. if (source.rotationQuaternion) {
  60208. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60209. }
  60210. _this.infiniteDistance = source.infiniteDistance;
  60211. _this.setPivotMatrix(source.getPivotMatrix());
  60212. _this.refreshBoundingInfo();
  60213. _this._syncSubMeshes();
  60214. return _this;
  60215. }
  60216. /**
  60217. * Returns the string "InstancedMesh".
  60218. */
  60219. InstancedMesh.prototype.getClassName = function () {
  60220. return "InstancedMesh";
  60221. };
  60222. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60223. // Methods
  60224. get: function () {
  60225. return this._sourceMesh.receiveShadows;
  60226. },
  60227. enumerable: true,
  60228. configurable: true
  60229. });
  60230. Object.defineProperty(InstancedMesh.prototype, "material", {
  60231. get: function () {
  60232. return this._sourceMesh.material;
  60233. },
  60234. enumerable: true,
  60235. configurable: true
  60236. });
  60237. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60238. get: function () {
  60239. return this._sourceMesh.visibility;
  60240. },
  60241. enumerable: true,
  60242. configurable: true
  60243. });
  60244. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60245. get: function () {
  60246. return this._sourceMesh.skeleton;
  60247. },
  60248. enumerable: true,
  60249. configurable: true
  60250. });
  60251. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60252. get: function () {
  60253. return this._sourceMesh.renderingGroupId;
  60254. },
  60255. set: function (value) {
  60256. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60257. return;
  60258. }
  60259. //no-op with warning
  60260. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60261. },
  60262. enumerable: true,
  60263. configurable: true
  60264. });
  60265. /**
  60266. * Returns the total number of vertices (integer).
  60267. */
  60268. InstancedMesh.prototype.getTotalVertices = function () {
  60269. return this._sourceMesh.getTotalVertices();
  60270. };
  60271. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60272. get: function () {
  60273. return this._sourceMesh;
  60274. },
  60275. enumerable: true,
  60276. configurable: true
  60277. });
  60278. /**
  60279. * Is this node ready to be used/rendered
  60280. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60281. * @return {boolean} is it ready
  60282. */
  60283. InstancedMesh.prototype.isReady = function (completeCheck) {
  60284. if (completeCheck === void 0) { completeCheck = false; }
  60285. return this._sourceMesh.isReady(completeCheck, true);
  60286. };
  60287. /**
  60288. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60289. */
  60290. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60291. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60292. };
  60293. /**
  60294. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60295. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60296. * The `data` are either a numeric array either a Float32Array.
  60297. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60298. * 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).
  60299. * Note that a new underlying VertexBuffer object is created each call.
  60300. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60301. *
  60302. * Possible `kind` values :
  60303. * - BABYLON.VertexBuffer.PositionKind
  60304. * - BABYLON.VertexBuffer.UVKind
  60305. * - BABYLON.VertexBuffer.UV2Kind
  60306. * - BABYLON.VertexBuffer.UV3Kind
  60307. * - BABYLON.VertexBuffer.UV4Kind
  60308. * - BABYLON.VertexBuffer.UV5Kind
  60309. * - BABYLON.VertexBuffer.UV6Kind
  60310. * - BABYLON.VertexBuffer.ColorKind
  60311. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60312. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60313. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60314. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60315. *
  60316. * Returns the Mesh.
  60317. */
  60318. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60319. if (this.sourceMesh) {
  60320. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60321. }
  60322. return this.sourceMesh;
  60323. };
  60324. /**
  60325. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60326. * If the mesh has no geometry, it is simply returned as it is.
  60327. * The `data` are either a numeric array either a Float32Array.
  60328. * No new underlying VertexBuffer object is created.
  60329. * 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.
  60330. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60331. *
  60332. * Possible `kind` values :
  60333. * - BABYLON.VertexBuffer.PositionKind
  60334. * - BABYLON.VertexBuffer.UVKind
  60335. * - BABYLON.VertexBuffer.UV2Kind
  60336. * - BABYLON.VertexBuffer.UV3Kind
  60337. * - BABYLON.VertexBuffer.UV4Kind
  60338. * - BABYLON.VertexBuffer.UV5Kind
  60339. * - BABYLON.VertexBuffer.UV6Kind
  60340. * - BABYLON.VertexBuffer.ColorKind
  60341. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60342. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60343. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60344. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60345. *
  60346. * Returns the Mesh.
  60347. */
  60348. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60349. if (this.sourceMesh) {
  60350. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60351. }
  60352. return this.sourceMesh;
  60353. };
  60354. /**
  60355. * Sets the mesh indices.
  60356. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60357. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60358. * This method creates a new index buffer each call.
  60359. * Returns the Mesh.
  60360. */
  60361. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60362. if (totalVertices === void 0) { totalVertices = null; }
  60363. if (this.sourceMesh) {
  60364. this.sourceMesh.setIndices(indices, totalVertices);
  60365. }
  60366. return this.sourceMesh;
  60367. };
  60368. /**
  60369. * Boolean : True if the mesh owns the requested kind of data.
  60370. */
  60371. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60372. return this._sourceMesh.isVerticesDataPresent(kind);
  60373. };
  60374. /**
  60375. * Returns an array of indices (IndicesArray).
  60376. */
  60377. InstancedMesh.prototype.getIndices = function () {
  60378. return this._sourceMesh.getIndices();
  60379. };
  60380. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60381. get: function () {
  60382. return this._sourceMesh._positions;
  60383. },
  60384. enumerable: true,
  60385. configurable: true
  60386. });
  60387. /**
  60388. * Sets a new updated BoundingInfo to the mesh.
  60389. * Returns the mesh.
  60390. */
  60391. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60392. var meshBB = this._sourceMesh.getBoundingInfo();
  60393. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60394. this._updateBoundingInfo();
  60395. return this;
  60396. };
  60397. InstancedMesh.prototype._preActivate = function () {
  60398. if (this._currentLOD) {
  60399. this._currentLOD._preActivate();
  60400. }
  60401. return this;
  60402. };
  60403. InstancedMesh.prototype._activate = function (renderId) {
  60404. if (this._currentLOD) {
  60405. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60406. }
  60407. return this;
  60408. };
  60409. /**
  60410. * Returns the current associated LOD AbstractMesh.
  60411. */
  60412. InstancedMesh.prototype.getLOD = function (camera) {
  60413. if (!camera) {
  60414. return this;
  60415. }
  60416. var boundingInfo = this.getBoundingInfo();
  60417. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60418. if (this._currentLOD === this.sourceMesh) {
  60419. return this;
  60420. }
  60421. return this._currentLOD;
  60422. };
  60423. InstancedMesh.prototype._syncSubMeshes = function () {
  60424. this.releaseSubMeshes();
  60425. if (this._sourceMesh.subMeshes) {
  60426. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60427. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60428. }
  60429. }
  60430. return this;
  60431. };
  60432. InstancedMesh.prototype._generatePointsArray = function () {
  60433. return this._sourceMesh._generatePointsArray();
  60434. };
  60435. /**
  60436. * Creates a new InstancedMesh from the current mesh.
  60437. * - name (string) : the cloned mesh name
  60438. * - newParent (optional Node) : the optional Node to parent the clone to.
  60439. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60440. *
  60441. * Returns the clone.
  60442. */
  60443. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60444. var result = this._sourceMesh.createInstance(name);
  60445. // Deep copy
  60446. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60447. // Bounding info
  60448. this.refreshBoundingInfo();
  60449. // Parent
  60450. if (newParent) {
  60451. result.parent = newParent;
  60452. }
  60453. if (!doNotCloneChildren) {
  60454. // Children
  60455. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60456. var mesh = this.getScene().meshes[index];
  60457. if (mesh.parent === this) {
  60458. mesh.clone(mesh.name, result);
  60459. }
  60460. }
  60461. }
  60462. result.computeWorldMatrix(true);
  60463. return result;
  60464. };
  60465. /**
  60466. * Disposes the InstancedMesh.
  60467. * Returns nothing.
  60468. */
  60469. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60470. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60471. // Remove from mesh
  60472. var index = this._sourceMesh.instances.indexOf(this);
  60473. this._sourceMesh.instances.splice(index, 1);
  60474. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60475. };
  60476. return InstancedMesh;
  60477. }(BABYLON.AbstractMesh));
  60478. BABYLON.InstancedMesh = InstancedMesh;
  60479. })(BABYLON || (BABYLON = {}));
  60480. //# sourceMappingURL=babylon.instancedMesh.js.map
  60481. var BABYLON;
  60482. (function (BABYLON) {
  60483. var LinesMesh = /** @class */ (function (_super) {
  60484. __extends(LinesMesh, _super);
  60485. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60486. if (scene === void 0) { scene = null; }
  60487. if (parent === void 0) { parent = null; }
  60488. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60489. _this.useVertexColor = useVertexColor;
  60490. _this.useVertexAlpha = useVertexAlpha;
  60491. _this.color = new BABYLON.Color3(1, 1, 1);
  60492. _this.alpha = 1;
  60493. if (source) {
  60494. _this.color = source.color.clone();
  60495. _this.alpha = source.alpha;
  60496. _this.useVertexColor = source.useVertexColor;
  60497. _this.useVertexAlpha = source.useVertexAlpha;
  60498. }
  60499. _this._intersectionThreshold = 0.1;
  60500. var defines = [];
  60501. var options = {
  60502. attributes: [BABYLON.VertexBuffer.PositionKind],
  60503. uniforms: ["world", "viewProjection"],
  60504. needAlphaBlending: true,
  60505. defines: defines
  60506. };
  60507. if (useVertexAlpha === false) {
  60508. options.needAlphaBlending = false;
  60509. }
  60510. if (!useVertexColor) {
  60511. options.uniforms.push("color");
  60512. }
  60513. else {
  60514. options.defines.push("#define VERTEXCOLOR");
  60515. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60516. }
  60517. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60518. return _this;
  60519. }
  60520. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60521. /**
  60522. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60523. * This margin is expressed in world space coordinates, so its value may vary.
  60524. * Default value is 0.1
  60525. * @returns the intersection Threshold value.
  60526. */
  60527. get: function () {
  60528. return this._intersectionThreshold;
  60529. },
  60530. /**
  60531. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60532. * This margin is expressed in world space coordinates, so its value may vary.
  60533. * @param value the new threshold to apply
  60534. */
  60535. set: function (value) {
  60536. if (this._intersectionThreshold === value) {
  60537. return;
  60538. }
  60539. this._intersectionThreshold = value;
  60540. if (this.geometry) {
  60541. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60542. }
  60543. },
  60544. enumerable: true,
  60545. configurable: true
  60546. });
  60547. /**
  60548. * Returns the string "LineMesh"
  60549. */
  60550. LinesMesh.prototype.getClassName = function () {
  60551. return "LinesMesh";
  60552. };
  60553. Object.defineProperty(LinesMesh.prototype, "material", {
  60554. get: function () {
  60555. return this._colorShader;
  60556. },
  60557. set: function (value) {
  60558. // Do nothing
  60559. },
  60560. enumerable: true,
  60561. configurable: true
  60562. });
  60563. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60564. get: function () {
  60565. return false;
  60566. },
  60567. enumerable: true,
  60568. configurable: true
  60569. });
  60570. LinesMesh.prototype.createInstance = function (name) {
  60571. throw new Error("LinesMeshes do not support createInstance.");
  60572. };
  60573. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60574. if (!this._geometry) {
  60575. return this;
  60576. }
  60577. // VBOs
  60578. this._geometry._bind(this._colorShader.getEffect());
  60579. // Color
  60580. if (!this.useVertexColor) {
  60581. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60582. }
  60583. return this;
  60584. };
  60585. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60586. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60587. return this;
  60588. }
  60589. var engine = this.getScene().getEngine();
  60590. // Draw order
  60591. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60592. return this;
  60593. };
  60594. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60595. this._colorShader.dispose();
  60596. _super.prototype.dispose.call(this, doNotRecurse);
  60597. };
  60598. /**
  60599. * Returns a new LineMesh object cloned from the current one.
  60600. */
  60601. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60602. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60603. };
  60604. return LinesMesh;
  60605. }(BABYLON.Mesh));
  60606. BABYLON.LinesMesh = LinesMesh;
  60607. })(BABYLON || (BABYLON = {}));
  60608. //# sourceMappingURL=babylon.linesMesh.js.map
  60609. var BABYLON;
  60610. (function (BABYLON) {
  60611. /**
  60612. * Class containing static functions to help procedurally build meshes
  60613. */
  60614. var MeshBuilder = /** @class */ (function () {
  60615. function MeshBuilder() {
  60616. }
  60617. MeshBuilder.updateSideOrientation = function (orientation) {
  60618. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60619. return BABYLON.Mesh.DOUBLESIDE;
  60620. }
  60621. if (orientation === undefined || orientation === null) {
  60622. return BABYLON.Mesh.FRONTSIDE;
  60623. }
  60624. return orientation;
  60625. };
  60626. /**
  60627. * Creates a box mesh
  60628. * * The parameter `size` sets the size (float) of each box side (default 1)
  60629. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60630. * * 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)
  60631. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60632. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60633. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60634. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60635. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60636. * @param name defines the name of the mesh
  60637. * @param options defines the options used to create the mesh
  60638. * @param scene defines the hosting scene
  60639. * @returns the box mesh
  60640. */
  60641. MeshBuilder.CreateBox = function (name, options, scene) {
  60642. if (scene === void 0) { scene = null; }
  60643. var box = new BABYLON.Mesh(name, scene);
  60644. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60645. box._originalBuilderSideOrientation = options.sideOrientation;
  60646. var vertexData = BABYLON.VertexData.CreateBox(options);
  60647. vertexData.applyToMesh(box, options.updatable);
  60648. return box;
  60649. };
  60650. /**
  60651. * Creates a sphere mesh
  60652. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60653. * * 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`)
  60654. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60655. * * 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
  60656. * * 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)
  60657. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60658. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60659. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60660. * @param name defines the name of the mesh
  60661. * @param options defines the options used to create the mesh
  60662. * @param scene defines the hosting scene
  60663. * @returns the sphere mesh
  60664. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60665. */
  60666. MeshBuilder.CreateSphere = function (name, options, scene) {
  60667. var sphere = new BABYLON.Mesh(name, scene);
  60668. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60669. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60670. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60671. vertexData.applyToMesh(sphere, options.updatable);
  60672. return sphere;
  60673. };
  60674. /**
  60675. * Creates a plane polygonal mesh. By default, this is a disc
  60676. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60677. * * 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
  60678. * * 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
  60679. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60680. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60681. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60682. * @param name defines the name of the mesh
  60683. * @param options defines the options used to create the mesh
  60684. * @param scene defines the hosting scene
  60685. * @returns the plane polygonal mesh
  60686. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60687. */
  60688. MeshBuilder.CreateDisc = function (name, options, scene) {
  60689. if (scene === void 0) { scene = null; }
  60690. var disc = new BABYLON.Mesh(name, scene);
  60691. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60692. disc._originalBuilderSideOrientation = options.sideOrientation;
  60693. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60694. vertexData.applyToMesh(disc, options.updatable);
  60695. return disc;
  60696. };
  60697. /**
  60698. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60699. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60700. * * 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`)
  60701. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60702. * * 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
  60703. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60704. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60705. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60706. * @param name defines the name of the mesh
  60707. * @param options defines the options used to create the mesh
  60708. * @param scene defines the hosting scene
  60709. * @returns the icosahedron mesh
  60710. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60711. */
  60712. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60713. var sphere = new BABYLON.Mesh(name, scene);
  60714. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60715. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60716. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60717. vertexData.applyToMesh(sphere, options.updatable);
  60718. return sphere;
  60719. };
  60720. ;
  60721. /**
  60722. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60723. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60724. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60725. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60726. * * 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
  60727. * * 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
  60728. * * 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
  60729. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60730. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60731. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60732. * * 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
  60733. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60734. * * 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 if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  60735. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60736. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60737. * @param name defines the name of the mesh
  60738. * @param options defines the options used to create the mesh
  60739. * @param scene defines the hosting scene
  60740. * @returns the ribbon mesh
  60741. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60742. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60743. */
  60744. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60745. if (scene === void 0) { scene = null; }
  60746. var pathArray = options.pathArray;
  60747. var closeArray = options.closeArray;
  60748. var closePath = options.closePath;
  60749. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60750. var instance = options.instance;
  60751. var updatable = options.updatable;
  60752. if (instance) { // existing ribbon instance update
  60753. // positionFunction : ribbon case
  60754. // only pathArray and sideOrientation parameters are taken into account for positions update
  60755. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60756. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60757. var positionFunction = function (positions) {
  60758. var minlg = pathArray[0].length;
  60759. var i = 0;
  60760. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60761. for (var si = 1; si <= ns; si++) {
  60762. for (var p = 0; p < pathArray.length; p++) {
  60763. var path = pathArray[p];
  60764. var l = path.length;
  60765. minlg = (minlg < l) ? minlg : l;
  60766. var j = 0;
  60767. while (j < minlg) {
  60768. positions[i] = path[j].x;
  60769. positions[i + 1] = path[j].y;
  60770. positions[i + 2] = path[j].z;
  60771. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60772. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60773. }
  60774. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60775. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60776. }
  60777. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60778. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60779. }
  60780. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60781. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60782. }
  60783. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60784. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60785. }
  60786. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60787. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60788. }
  60789. j++;
  60790. i += 3;
  60791. }
  60792. if (instance._closePath) {
  60793. positions[i] = path[0].x;
  60794. positions[i + 1] = path[0].y;
  60795. positions[i + 2] = path[0].z;
  60796. i += 3;
  60797. }
  60798. }
  60799. }
  60800. };
  60801. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60802. positionFunction(positions);
  60803. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60804. instance._boundingInfo.update(instance._worldMatrix);
  60805. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60806. if (options.colors) {
  60807. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60808. for (var c = 0; c < options.colors.length; c++) {
  60809. colors[c * 4] = options.colors[c].r;
  60810. colors[c * 4 + 1] = options.colors[c].g;
  60811. colors[c * 4 + 2] = options.colors[c].b;
  60812. colors[c * 4 + 3] = options.colors[c].a;
  60813. }
  60814. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60815. }
  60816. if (options.uvs) {
  60817. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60818. for (var i = 0; i < options.uvs.length; i++) {
  60819. uvs[i * 2] = options.uvs[i].x;
  60820. uvs[i * 2 + 1] = options.uvs[i].y;
  60821. }
  60822. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60823. }
  60824. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60825. var indices = instance.getIndices();
  60826. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60827. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60828. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60829. if (instance._closePath) {
  60830. var indexFirst = 0;
  60831. var indexLast = 0;
  60832. for (var p = 0; p < pathArray.length; p++) {
  60833. indexFirst = instance._idx[p] * 3;
  60834. if (p + 1 < pathArray.length) {
  60835. indexLast = (instance._idx[p + 1] - 1) * 3;
  60836. }
  60837. else {
  60838. indexLast = normals.length - 3;
  60839. }
  60840. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60841. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60842. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60843. normals[indexLast] = normals[indexFirst];
  60844. normals[indexLast + 1] = normals[indexFirst + 1];
  60845. normals[indexLast + 2] = normals[indexFirst + 2];
  60846. }
  60847. }
  60848. if (!(instance.areNormalsFrozen)) {
  60849. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60850. }
  60851. }
  60852. return instance;
  60853. }
  60854. else { // new ribbon creation
  60855. var ribbon = new BABYLON.Mesh(name, scene);
  60856. ribbon._originalBuilderSideOrientation = sideOrientation;
  60857. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60858. if (closePath) {
  60859. ribbon._idx = vertexData._idx;
  60860. }
  60861. ribbon._closePath = closePath;
  60862. ribbon._closeArray = closeArray;
  60863. vertexData.applyToMesh(ribbon, updatable);
  60864. return ribbon;
  60865. }
  60866. };
  60867. /**
  60868. * Creates a cylinder or a cone mesh
  60869. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60870. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60871. * * 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.
  60872. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60873. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60874. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60875. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60876. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60877. * * 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).
  60878. * * 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
  60879. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60880. * * 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
  60881. * * 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.
  60882. * * If `enclose` is false, a ring surface is one element.
  60883. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60884. * * 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
  60885. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60886. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60887. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60888. * @param name defines the name of the mesh
  60889. * @param options defines the options used to create the mesh
  60890. * @param scene defines the hosting scene
  60891. * @returns the cylinder mesh
  60892. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60893. */
  60894. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60895. var cylinder = new BABYLON.Mesh(name, scene);
  60896. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60897. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60898. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60899. vertexData.applyToMesh(cylinder, options.updatable);
  60900. return cylinder;
  60901. };
  60902. /**
  60903. * Creates a torus mesh
  60904. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60905. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60906. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60907. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60908. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60909. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60910. * @param name defines the name of the mesh
  60911. * @param options defines the options used to create the mesh
  60912. * @param scene defines the hosting scene
  60913. * @returns the torus mesh
  60914. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60915. */
  60916. MeshBuilder.CreateTorus = function (name, options, scene) {
  60917. var torus = new BABYLON.Mesh(name, scene);
  60918. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60919. torus._originalBuilderSideOrientation = options.sideOrientation;
  60920. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60921. vertexData.applyToMesh(torus, options.updatable);
  60922. return torus;
  60923. };
  60924. /**
  60925. * Creates a torus knot mesh
  60926. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60927. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60928. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60929. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60930. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60931. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60932. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60933. * @param name defines the name of the mesh
  60934. * @param options defines the options used to create the mesh
  60935. * @param scene defines the hosting scene
  60936. * @returns the torus knot mesh
  60937. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60938. */
  60939. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60940. var torusKnot = new BABYLON.Mesh(name, scene);
  60941. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60942. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60943. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60944. vertexData.applyToMesh(torusKnot, options.updatable);
  60945. return torusKnot;
  60946. };
  60947. /**
  60948. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60949. * * 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
  60950. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60951. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60952. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60953. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60954. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60955. * * 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
  60956. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60957. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60958. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60959. * @param name defines the name of the new line system
  60960. * @param options defines the options used to create the line system
  60961. * @param scene defines the hosting scene
  60962. * @returns a new line system mesh
  60963. */
  60964. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60965. var instance = options.instance;
  60966. var lines = options.lines;
  60967. var colors = options.colors;
  60968. if (instance) { // lines update
  60969. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60970. var vertexColor;
  60971. var lineColors;
  60972. if (colors) {
  60973. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60974. }
  60975. var i = 0;
  60976. var c = 0;
  60977. for (var l = 0; l < lines.length; l++) {
  60978. var points = lines[l];
  60979. for (var p = 0; p < points.length; p++) {
  60980. positions[i] = points[p].x;
  60981. positions[i + 1] = points[p].y;
  60982. positions[i + 2] = points[p].z;
  60983. if (colors && vertexColor) {
  60984. lineColors = colors[l];
  60985. vertexColor[c] = lineColors[p].r;
  60986. vertexColor[c + 1] = lineColors[p].g;
  60987. vertexColor[c + 2] = lineColors[p].b;
  60988. vertexColor[c + 3] = lineColors[p].a;
  60989. c += 4;
  60990. }
  60991. i += 3;
  60992. }
  60993. }
  60994. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60995. if (colors && vertexColor) {
  60996. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60997. }
  60998. return instance;
  60999. }
  61000. // line system creation
  61001. var useVertexColor = (colors) ? true : false;
  61002. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61003. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61004. vertexData.applyToMesh(lineSystem, options.updatable);
  61005. return lineSystem;
  61006. };
  61007. /**
  61008. * Creates a line mesh
  61009. * 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
  61010. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61011. * * The parameter `points` is an array successive Vector3
  61012. * * 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
  61013. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61014. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61015. * * When updating an instance, remember that only point positions can change, not the number of points
  61016. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61017. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61018. * @param name defines the name of the new line system
  61019. * @param options defines the options used to create the line system
  61020. * @param scene defines the hosting scene
  61021. * @returns a new line mesh
  61022. */
  61023. MeshBuilder.CreateLines = function (name, options, scene) {
  61024. if (scene === void 0) { scene = null; }
  61025. var colors = (options.colors) ? [options.colors] : null;
  61026. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61027. return lines;
  61028. };
  61029. /**
  61030. * Creates a dashed line mesh
  61031. * * 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
  61032. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61033. * * The parameter `points` is an array successive Vector3
  61034. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61035. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61036. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61037. * * 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
  61038. * * When updating an instance, remember that only point positions can change, not the number of points
  61039. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61040. * @param name defines the name of the mesh
  61041. * @param options defines the options used to create the mesh
  61042. * @param scene defines the hosting scene
  61043. * @returns the dashed line mesh
  61044. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61045. */
  61046. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61047. if (scene === void 0) { scene = null; }
  61048. var points = options.points;
  61049. var instance = options.instance;
  61050. var gapSize = options.gapSize || 1;
  61051. var dashSize = options.dashSize || 3;
  61052. if (instance) { // dashed lines update
  61053. var positionFunction = function (positions) {
  61054. var curvect = BABYLON.Vector3.Zero();
  61055. var nbSeg = positions.length / 6;
  61056. var lg = 0;
  61057. var nb = 0;
  61058. var shft = 0;
  61059. var dashshft = 0;
  61060. var curshft = 0;
  61061. var p = 0;
  61062. var i = 0;
  61063. var j = 0;
  61064. for (i = 0; i < points.length - 1; i++) {
  61065. points[i + 1].subtractToRef(points[i], curvect);
  61066. lg += curvect.length();
  61067. }
  61068. shft = lg / nbSeg;
  61069. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61070. for (i = 0; i < points.length - 1; i++) {
  61071. points[i + 1].subtractToRef(points[i], curvect);
  61072. nb = Math.floor(curvect.length() / shft);
  61073. curvect.normalize();
  61074. j = 0;
  61075. while (j < nb && p < positions.length) {
  61076. curshft = shft * j;
  61077. positions[p] = points[i].x + curshft * curvect.x;
  61078. positions[p + 1] = points[i].y + curshft * curvect.y;
  61079. positions[p + 2] = points[i].z + curshft * curvect.z;
  61080. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61081. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61082. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61083. p += 6;
  61084. j++;
  61085. }
  61086. }
  61087. while (p < positions.length) {
  61088. positions[p] = points[i].x;
  61089. positions[p + 1] = points[i].y;
  61090. positions[p + 2] = points[i].z;
  61091. p += 3;
  61092. }
  61093. };
  61094. instance.updateMeshPositions(positionFunction, false);
  61095. return instance;
  61096. }
  61097. // dashed lines creation
  61098. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61099. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61100. vertexData.applyToMesh(dashedLines, options.updatable);
  61101. dashedLines.dashSize = dashSize;
  61102. dashedLines.gapSize = gapSize;
  61103. return dashedLines;
  61104. };
  61105. /**
  61106. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61107. * * 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 extruded along the Z axis.
  61108. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61109. * * 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.
  61110. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61111. * * 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
  61112. * * 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
  61113. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61114. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61115. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61116. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61117. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61118. * @param name defines the name of the mesh
  61119. * @param options defines the options used to create the mesh
  61120. * @param scene defines the hosting scene
  61121. * @returns the extruded shape mesh
  61122. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61123. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61124. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61125. */
  61126. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61127. if (scene === void 0) { scene = null; }
  61128. var path = options.path;
  61129. var shape = options.shape;
  61130. var scale = options.scale || 1;
  61131. var rotation = options.rotation || 0;
  61132. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61133. var updatable = options.updatable;
  61134. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61135. var instance = options.instance || null;
  61136. var invertUV = options.invertUV || false;
  61137. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null);
  61138. };
  61139. /**
  61140. * Creates an custom extruded shape mesh.
  61141. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61142. * * 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 extruded along the Z axis.
  61143. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61144. * * 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 and the distance of this point from the begining of the path
  61145. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61146. * * 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 and the distance of this point from the begining of the path
  61147. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61148. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61149. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61150. * * 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
  61151. * * 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
  61152. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61153. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61154. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61155. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61156. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61157. * @param name defines the name of the mesh
  61158. * @param options defines the options used to create the mesh
  61159. * @param scene defines the hosting scene
  61160. * @returns the custom extruded shape mesh
  61161. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61162. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61163. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61164. */
  61165. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61166. var path = options.path;
  61167. var shape = options.shape;
  61168. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61169. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61170. var ribbonCloseArray = options.ribbonCloseArray || false;
  61171. var ribbonClosePath = options.ribbonClosePath || false;
  61172. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61173. var updatable = options.updatable;
  61174. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61175. var instance = options.instance;
  61176. var invertUV = options.invertUV || false;
  61177. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null);
  61178. };
  61179. /**
  61180. * Creates lathe mesh.
  61181. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61182. * * 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 rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  61183. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61184. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61185. * * 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
  61186. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61187. * * 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
  61188. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61189. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61190. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61191. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61192. * @param name defines the name of the mesh
  61193. * @param options defines the options used to create the mesh
  61194. * @param scene defines the hosting scene
  61195. * @returns the lathe mesh
  61196. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61197. */
  61198. MeshBuilder.CreateLathe = function (name, options, scene) {
  61199. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61200. var closed = (options.closed === undefined) ? true : options.closed;
  61201. var shape = options.shape;
  61202. var radius = options.radius || 1;
  61203. var tessellation = options.tessellation || 64;
  61204. var updatable = options.updatable;
  61205. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61206. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61207. var pi2 = Math.PI * 2;
  61208. var paths = new Array();
  61209. var invertUV = options.invertUV || false;
  61210. var i = 0;
  61211. var p = 0;
  61212. var step = pi2 / tessellation * arc;
  61213. var rotated;
  61214. var path = new Array();
  61215. for (i = 0; i <= tessellation; i++) {
  61216. var path = [];
  61217. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61218. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61219. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61220. }
  61221. for (p = 0; p < shape.length; p++) {
  61222. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61223. path.push(rotated);
  61224. }
  61225. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61226. 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));
  61227. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61228. }
  61229. paths.push(path);
  61230. }
  61231. // lathe ribbon
  61232. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61233. return lathe;
  61234. };
  61235. /**
  61236. * Creates a plane mesh
  61237. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61238. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61239. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61240. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61241. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61242. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61243. * @param name defines the name of the mesh
  61244. * @param options defines the options used to create the mesh
  61245. * @param scene defines the hosting scene
  61246. * @returns the plane mesh
  61247. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61248. */
  61249. MeshBuilder.CreatePlane = function (name, options, scene) {
  61250. var plane = new BABYLON.Mesh(name, scene);
  61251. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61252. plane._originalBuilderSideOrientation = options.sideOrientation;
  61253. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61254. vertexData.applyToMesh(plane, options.updatable);
  61255. if (options.sourcePlane) {
  61256. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61257. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61258. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61259. plane.rotate(vectorProduct, product);
  61260. }
  61261. return plane;
  61262. };
  61263. /**
  61264. * Creates a ground mesh
  61265. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61266. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61267. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61268. * @param name defines the name of the mesh
  61269. * @param options defines the options used to create the mesh
  61270. * @param scene defines the hosting scene
  61271. * @returns the ground mesh
  61272. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61273. */
  61274. MeshBuilder.CreateGround = function (name, options, scene) {
  61275. var ground = new BABYLON.GroundMesh(name, scene);
  61276. ground._setReady(false);
  61277. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61278. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61279. ground._width = options.width || 1;
  61280. ground._height = options.height || 1;
  61281. ground._maxX = ground._width / 2;
  61282. ground._maxZ = ground._height / 2;
  61283. ground._minX = -ground._maxX;
  61284. ground._minZ = -ground._maxZ;
  61285. var vertexData = BABYLON.VertexData.CreateGround(options);
  61286. vertexData.applyToMesh(ground, options.updatable);
  61287. ground._setReady(true);
  61288. return ground;
  61289. };
  61290. /**
  61291. * Creates a tiled ground mesh
  61292. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61293. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61294. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  61295. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  61296. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61297. * @param name defines the name of the mesh
  61298. * @param options defines the options used to create the mesh
  61299. * @param scene defines the hosting scene
  61300. * @returns the tiled ground mesh
  61301. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61302. */
  61303. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61304. var tiledGround = new BABYLON.Mesh(name, scene);
  61305. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61306. vertexData.applyToMesh(tiledGround, options.updatable);
  61307. return tiledGround;
  61308. };
  61309. /**
  61310. * Creates a ground mesh from a height map
  61311. * * The parameter `url` sets the URL of the height map image resource.
  61312. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61313. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61314. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61315. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61316. * * 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.
  61317. * * 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).
  61318. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61319. * @param name defines the name of the mesh
  61320. * @param url defines the url to the height map
  61321. * @param options defines the options used to create the mesh
  61322. * @param scene defines the hosting scene
  61323. * @returns the ground mesh
  61324. * @see http://doc.babylonjs.com/babylon101/height_map
  61325. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61326. */
  61327. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61328. var width = options.width || 10.0;
  61329. var height = options.height || 10.0;
  61330. var subdivisions = options.subdivisions || 1 | 0;
  61331. var minHeight = options.minHeight || 0.0;
  61332. var maxHeight = options.maxHeight || 1.0;
  61333. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61334. var updatable = options.updatable;
  61335. var onReady = options.onReady;
  61336. var ground = new BABYLON.GroundMesh(name, scene);
  61337. ground._subdivisionsX = subdivisions;
  61338. ground._subdivisionsY = subdivisions;
  61339. ground._width = width;
  61340. ground._height = height;
  61341. ground._maxX = ground._width / 2.0;
  61342. ground._maxZ = ground._height / 2.0;
  61343. ground._minX = -ground._maxX;
  61344. ground._minZ = -ground._maxZ;
  61345. ground._setReady(false);
  61346. var onload = function (img) {
  61347. // Getting height map data
  61348. var canvas = document.createElement("canvas");
  61349. var context = canvas.getContext("2d");
  61350. if (!context) {
  61351. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61352. }
  61353. if (scene.isDisposed) {
  61354. return;
  61355. }
  61356. var bufferWidth = img.width;
  61357. var bufferHeight = img.height;
  61358. canvas.width = bufferWidth;
  61359. canvas.height = bufferHeight;
  61360. context.drawImage(img, 0, 0);
  61361. // Create VertexData from map data
  61362. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61363. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61364. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61365. width: width, height: height,
  61366. subdivisions: subdivisions,
  61367. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61368. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61369. });
  61370. vertexData.applyToMesh(ground, updatable);
  61371. //execute ready callback, if set
  61372. if (onReady) {
  61373. onReady(ground);
  61374. }
  61375. ground._setReady(true);
  61376. };
  61377. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61378. return ground;
  61379. };
  61380. /**
  61381. * Creates a polygon mesh
  61382. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61383. * * 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
  61384. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61385. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61386. * * 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)
  61387. * * Remember you can only change the shape positions, not their number when updating a polygon
  61388. * @param name defines the name of the mesh
  61389. * @param options defines the options used to create the mesh
  61390. * @param scene defines the hosting scene
  61391. * @returns the polygon mesh
  61392. */
  61393. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61394. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61395. var shape = options.shape;
  61396. var holes = options.holes || [];
  61397. var depth = options.depth || 0;
  61398. var contours = [];
  61399. var hole = [];
  61400. for (var i = 0; i < shape.length; i++) {
  61401. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61402. }
  61403. var epsilon = 0.00000001;
  61404. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61405. contours.pop();
  61406. }
  61407. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61408. for (var hNb = 0; hNb < holes.length; hNb++) {
  61409. hole = [];
  61410. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61411. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61412. }
  61413. polygonTriangulation.addHole(hole);
  61414. }
  61415. var polygon = polygonTriangulation.build(options.updatable, depth);
  61416. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61417. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61418. vertexData.applyToMesh(polygon, options.updatable);
  61419. return polygon;
  61420. };
  61421. ;
  61422. /**
  61423. * Creates an extruded polygon mesh, with depth in the Y direction.
  61424. * * 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)
  61425. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61426. * @param name defines the name of the mesh
  61427. * @param options defines the options used to create the mesh
  61428. * @param scene defines the hosting scene
  61429. * @returns the polygon mesh
  61430. */
  61431. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61432. return MeshBuilder.CreatePolygon(name, options, scene);
  61433. };
  61434. ;
  61435. /**
  61436. * Creates a tube mesh.
  61437. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61438. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61439. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61440. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61441. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61442. * * 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. It must return a radius value (positive float)
  61443. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61444. * * 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
  61445. * * 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
  61446. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61447. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61448. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61449. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61450. * @param name defines the name of the mesh
  61451. * @param options defines the options used to create the mesh
  61452. * @param scene defines the hosting scene
  61453. * @returns the tube mesh
  61454. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61455. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61456. */
  61457. MeshBuilder.CreateTube = function (name, options, scene) {
  61458. var path = options.path;
  61459. var instance = options.instance;
  61460. var radius = 1.0;
  61461. if (instance) {
  61462. radius = instance.radius;
  61463. }
  61464. if (options.radius !== undefined) {
  61465. radius = options.radius;
  61466. }
  61467. ;
  61468. var tessellation = options.tessellation || 64 | 0;
  61469. var radiusFunction = options.radiusFunction || null;
  61470. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61471. var invertUV = options.invertUV || false;
  61472. var updatable = options.updatable;
  61473. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61474. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61475. // tube geometry
  61476. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61477. var tangents = path3D.getTangents();
  61478. var normals = path3D.getNormals();
  61479. var distances = path3D.getDistances();
  61480. var pi2 = Math.PI * 2;
  61481. var step = pi2 / tessellation * arc;
  61482. var returnRadius = function () { return radius; };
  61483. var radiusFunctionFinal = radiusFunction || returnRadius;
  61484. var circlePath;
  61485. var rad;
  61486. var normal;
  61487. var rotated;
  61488. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61489. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61490. for (var i = 0; i < path.length; i++) {
  61491. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61492. circlePath = Array(); // current circle array
  61493. normal = normals[i]; // current normal
  61494. for (var t = 0; t < tessellation; t++) {
  61495. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61496. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61497. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61498. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61499. circlePath[t] = rotated;
  61500. }
  61501. circlePaths[index] = circlePath;
  61502. index++;
  61503. }
  61504. // cap
  61505. var capPath = function (nbPoints, pathIndex) {
  61506. var pointCap = Array();
  61507. for (var i = 0; i < nbPoints; i++) {
  61508. pointCap.push(path[pathIndex]);
  61509. }
  61510. return pointCap;
  61511. };
  61512. switch (cap) {
  61513. case BABYLON.Mesh.NO_CAP:
  61514. break;
  61515. case BABYLON.Mesh.CAP_START:
  61516. circlePaths[0] = capPath(tessellation, 0);
  61517. circlePaths[1] = circlePaths[2].slice(0);
  61518. break;
  61519. case BABYLON.Mesh.CAP_END:
  61520. circlePaths[index] = circlePaths[index - 1].slice(0);
  61521. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61522. break;
  61523. case BABYLON.Mesh.CAP_ALL:
  61524. circlePaths[0] = capPath(tessellation, 0);
  61525. circlePaths[1] = circlePaths[2].slice(0);
  61526. circlePaths[index] = circlePaths[index - 1].slice(0);
  61527. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61528. break;
  61529. default:
  61530. break;
  61531. }
  61532. return circlePaths;
  61533. };
  61534. var path3D;
  61535. var pathArray;
  61536. if (instance) { // tube update
  61537. var arc = options.arc || instance.arc;
  61538. path3D = (instance.path3D).update(path);
  61539. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61540. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61541. instance.path3D = path3D;
  61542. instance.pathArray = pathArray;
  61543. instance.arc = arc;
  61544. instance.radius = radius;
  61545. return instance;
  61546. }
  61547. // tube creation
  61548. path3D = new BABYLON.Path3D(path);
  61549. var newPathArray = new Array();
  61550. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61551. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61552. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61553. tube.pathArray = pathArray;
  61554. tube.path3D = path3D;
  61555. tube.tessellation = tessellation;
  61556. tube.cap = cap;
  61557. tube.arc = options.arc;
  61558. tube.radius = radius;
  61559. return tube;
  61560. };
  61561. /**
  61562. * Creates a polyhedron mesh
  61563. * * 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 to choose the wanted type
  61564. * * The parameter `size` (positive float, default 1) sets the polygon size
  61565. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61566. * * 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`
  61567. * * 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
  61568. * * 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)`)
  61569. * * 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
  61570. * * 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
  61571. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61572. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61573. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61574. * @param name defines the name of the mesh
  61575. * @param options defines the options used to create the mesh
  61576. * @param scene defines the hosting scene
  61577. * @returns the polyhedron mesh
  61578. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61579. */
  61580. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61581. var polyhedron = new BABYLON.Mesh(name, scene);
  61582. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61583. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61584. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61585. vertexData.applyToMesh(polyhedron, options.updatable);
  61586. return polyhedron;
  61587. };
  61588. /**
  61589. * Creates a decal mesh.
  61590. * 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
  61591. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61592. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61593. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61594. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61595. * @param name defines the name of the mesh
  61596. * @param sourceMesh defines the mesh where the decal must be applied
  61597. * @param options defines the options used to create the mesh
  61598. * @param scene defines the hosting scene
  61599. * @returns the decal mesh
  61600. * @see http://doc.babylonjs.com/how_to/decals
  61601. */
  61602. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61603. var indices = sourceMesh.getIndices();
  61604. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61605. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61606. var position = options.position || BABYLON.Vector3.Zero();
  61607. var normal = options.normal || BABYLON.Vector3.Up();
  61608. var size = options.size || BABYLON.Vector3.One();
  61609. var angle = options.angle || 0;
  61610. // Getting correct rotation
  61611. if (!normal) {
  61612. var target = new BABYLON.Vector3(0, 0, 1);
  61613. var camera = sourceMesh.getScene().activeCamera;
  61614. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61615. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61616. }
  61617. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61618. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61619. var pitch = Math.atan2(normal.y, len);
  61620. // Matrix
  61621. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61622. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61623. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61624. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61625. var vertexData = new BABYLON.VertexData();
  61626. vertexData.indices = [];
  61627. vertexData.positions = [];
  61628. vertexData.normals = [];
  61629. vertexData.uvs = [];
  61630. var currentVertexDataIndex = 0;
  61631. var extractDecalVector3 = function (indexId) {
  61632. var result = new BABYLON.PositionNormalVertex();
  61633. if (!indices || !positions || !normals) {
  61634. return result;
  61635. }
  61636. var vertexId = indices[indexId];
  61637. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61638. // Send vector to decal local world
  61639. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61640. // Get normal
  61641. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61642. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61643. return result;
  61644. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61645. var clip = function (vertices, axis) {
  61646. if (vertices.length === 0) {
  61647. return vertices;
  61648. }
  61649. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61650. var clipVertices = function (v0, v1) {
  61651. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61652. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61653. };
  61654. var result = new Array();
  61655. for (var index = 0; index < vertices.length; index += 3) {
  61656. var v1Out;
  61657. var v2Out;
  61658. var v3Out;
  61659. var total = 0;
  61660. var nV1 = null;
  61661. var nV2 = null;
  61662. var nV3 = null;
  61663. var nV4 = null;
  61664. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61665. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61666. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61667. v1Out = d1 > 0;
  61668. v2Out = d2 > 0;
  61669. v3Out = d3 > 0;
  61670. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61671. switch (total) {
  61672. case 0:
  61673. result.push(vertices[index]);
  61674. result.push(vertices[index + 1]);
  61675. result.push(vertices[index + 2]);
  61676. break;
  61677. case 1:
  61678. if (v1Out) {
  61679. nV1 = vertices[index + 1];
  61680. nV2 = vertices[index + 2];
  61681. nV3 = clipVertices(vertices[index], nV1);
  61682. nV4 = clipVertices(vertices[index], nV2);
  61683. }
  61684. if (v2Out) {
  61685. nV1 = vertices[index];
  61686. nV2 = vertices[index + 2];
  61687. nV3 = clipVertices(vertices[index + 1], nV1);
  61688. nV4 = clipVertices(vertices[index + 1], nV2);
  61689. result.push(nV3);
  61690. result.push(nV2.clone());
  61691. result.push(nV1.clone());
  61692. result.push(nV2.clone());
  61693. result.push(nV3.clone());
  61694. result.push(nV4);
  61695. break;
  61696. }
  61697. if (v3Out) {
  61698. nV1 = vertices[index];
  61699. nV2 = vertices[index + 1];
  61700. nV3 = clipVertices(vertices[index + 2], nV1);
  61701. nV4 = clipVertices(vertices[index + 2], nV2);
  61702. }
  61703. if (nV1 && nV2 && nV3 && nV4) {
  61704. result.push(nV1.clone());
  61705. result.push(nV2.clone());
  61706. result.push(nV3);
  61707. result.push(nV4);
  61708. result.push(nV3.clone());
  61709. result.push(nV2.clone());
  61710. }
  61711. break;
  61712. case 2:
  61713. if (!v1Out) {
  61714. nV1 = vertices[index].clone();
  61715. nV2 = clipVertices(nV1, vertices[index + 1]);
  61716. nV3 = clipVertices(nV1, vertices[index + 2]);
  61717. result.push(nV1);
  61718. result.push(nV2);
  61719. result.push(nV3);
  61720. }
  61721. if (!v2Out) {
  61722. nV1 = vertices[index + 1].clone();
  61723. nV2 = clipVertices(nV1, vertices[index + 2]);
  61724. nV3 = clipVertices(nV1, vertices[index]);
  61725. result.push(nV1);
  61726. result.push(nV2);
  61727. result.push(nV3);
  61728. }
  61729. if (!v3Out) {
  61730. nV1 = vertices[index + 2].clone();
  61731. nV2 = clipVertices(nV1, vertices[index]);
  61732. nV3 = clipVertices(nV1, vertices[index + 1]);
  61733. result.push(nV1);
  61734. result.push(nV2);
  61735. result.push(nV3);
  61736. }
  61737. break;
  61738. case 3:
  61739. break;
  61740. }
  61741. }
  61742. return result;
  61743. };
  61744. for (var index = 0; index < indices.length; index += 3) {
  61745. var faceVertices = new Array();
  61746. faceVertices.push(extractDecalVector3(index));
  61747. faceVertices.push(extractDecalVector3(index + 1));
  61748. faceVertices.push(extractDecalVector3(index + 2));
  61749. // Clip
  61750. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61751. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61752. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61753. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61754. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61755. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61756. if (faceVertices.length === 0) {
  61757. continue;
  61758. }
  61759. // Add UVs and get back to world
  61760. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61761. var vertex = faceVertices[vIndex];
  61762. //TODO check for Int32Array | Uint32Array | Uint16Array
  61763. vertexData.indices.push(currentVertexDataIndex);
  61764. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61765. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61766. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61767. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61768. currentVertexDataIndex++;
  61769. }
  61770. }
  61771. // Return mesh
  61772. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61773. vertexData.applyToMesh(decal);
  61774. decal.position = position.clone();
  61775. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61776. return decal;
  61777. };
  61778. // Privates
  61779. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61780. // extrusion geometry
  61781. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61782. var tangents = path3D.getTangents();
  61783. var normals = path3D.getNormals();
  61784. var binormals = path3D.getBinormals();
  61785. var distances = path3D.getDistances();
  61786. var angle = 0;
  61787. var returnScale = function () { return scale !== null ? scale : 1; };
  61788. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61789. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61790. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61791. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61792. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61793. for (var i = 0; i < curve.length; i++) {
  61794. var shapePath = new Array();
  61795. var angleStep = rotate(i, distances[i]);
  61796. var scaleRatio = scl(i, distances[i]);
  61797. for (var p = 0; p < shape.length; p++) {
  61798. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61799. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61800. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61801. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61802. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61803. shapePath[p] = rotated;
  61804. }
  61805. shapePaths[index] = shapePath;
  61806. angle += angleStep;
  61807. index++;
  61808. }
  61809. // cap
  61810. var capPath = function (shapePath) {
  61811. var pointCap = Array();
  61812. var barycenter = BABYLON.Vector3.Zero();
  61813. var i;
  61814. for (i = 0; i < shapePath.length; i++) {
  61815. barycenter.addInPlace(shapePath[i]);
  61816. }
  61817. barycenter.scaleInPlace(1.0 / shapePath.length);
  61818. for (i = 0; i < shapePath.length; i++) {
  61819. pointCap.push(barycenter);
  61820. }
  61821. return pointCap;
  61822. };
  61823. switch (cap) {
  61824. case BABYLON.Mesh.NO_CAP:
  61825. break;
  61826. case BABYLON.Mesh.CAP_START:
  61827. shapePaths[0] = capPath(shapePaths[2]);
  61828. shapePaths[1] = shapePaths[2];
  61829. break;
  61830. case BABYLON.Mesh.CAP_END:
  61831. shapePaths[index] = shapePaths[index - 1];
  61832. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61833. break;
  61834. case BABYLON.Mesh.CAP_ALL:
  61835. shapePaths[0] = capPath(shapePaths[2]);
  61836. shapePaths[1] = shapePaths[2];
  61837. shapePaths[index] = shapePaths[index - 1];
  61838. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61839. break;
  61840. default:
  61841. break;
  61842. }
  61843. return shapePaths;
  61844. };
  61845. var path3D;
  61846. var pathArray;
  61847. if (instance) { // instance update
  61848. path3D = (instance.path3D).update(curve);
  61849. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61850. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61851. return instance;
  61852. }
  61853. // extruded shape creation
  61854. path3D = new BABYLON.Path3D(curve);
  61855. var newShapePaths = new Array();
  61856. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61857. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61858. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61859. extrudedGeneric.pathArray = pathArray;
  61860. extrudedGeneric.path3D = path3D;
  61861. extrudedGeneric.cap = cap;
  61862. return extrudedGeneric;
  61863. };
  61864. return MeshBuilder;
  61865. }());
  61866. BABYLON.MeshBuilder = MeshBuilder;
  61867. })(BABYLON || (BABYLON = {}));
  61868. //# sourceMappingURL=babylon.meshBuilder.js.map
  61869. var BABYLON;
  61870. (function (BABYLON) {
  61871. /**
  61872. * Draco compression (https://google.github.io/draco/)
  61873. *
  61874. * This class wraps the Draco module.
  61875. *
  61876. * **Encoder**
  61877. *
  61878. * The encoder is not currently implemented.
  61879. *
  61880. * **Decoder**
  61881. *
  61882. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61883. *
  61884. * To update the configuration, use the following code:
  61885. * ```javascript
  61886. * BABYLON.DracoCompression.Configuration = {
  61887. * decoder: {
  61888. * wasmUrl: "<url to the WebAssembly library>",
  61889. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61890. * fallbackUrl: "<url to the fallback JavaScript library>",
  61891. * }
  61892. * };
  61893. * ```
  61894. *
  61895. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  61896. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61897. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61898. *
  61899. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61900. * ```javascript
  61901. * var dracoCompression = new BABYLON.DracoCompression();
  61902. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61903. * [BABYLON.VertexBuffer.PositionKind]: 0
  61904. * });
  61905. * ```
  61906. *
  61907. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61908. */
  61909. var DracoCompression = /** @class */ (function () {
  61910. /**
  61911. * Constructor
  61912. */
  61913. function DracoCompression() {
  61914. }
  61915. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61916. /**
  61917. * Returns true if the decoder is available.
  61918. */
  61919. get: function () {
  61920. if (typeof DracoDecoderModule !== "undefined") {
  61921. return true;
  61922. }
  61923. var decoder = DracoCompression.Configuration.decoder;
  61924. if (decoder) {
  61925. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61926. return true;
  61927. }
  61928. if (decoder.fallbackUrl) {
  61929. return true;
  61930. }
  61931. }
  61932. return false;
  61933. },
  61934. enumerable: true,
  61935. configurable: true
  61936. });
  61937. /**
  61938. * Stop all async operations and release resources.
  61939. */
  61940. DracoCompression.prototype.dispose = function () {
  61941. };
  61942. /**
  61943. * Decode Draco compressed mesh data to vertex data.
  61944. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61945. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61946. * @returns A promise that resolves with the decoded vertex data
  61947. */
  61948. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61949. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61950. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61951. var module = wrappedModule.module;
  61952. var vertexData = new BABYLON.VertexData();
  61953. var buffer = new module.DecoderBuffer();
  61954. buffer.Init(dataView, dataView.byteLength);
  61955. var decoder = new module.Decoder();
  61956. var geometry;
  61957. var status;
  61958. try {
  61959. var type = decoder.GetEncodedGeometryType(buffer);
  61960. switch (type) {
  61961. case module.TRIANGULAR_MESH:
  61962. geometry = new module.Mesh();
  61963. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61964. break;
  61965. case module.POINT_CLOUD:
  61966. geometry = new module.PointCloud();
  61967. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61968. break;
  61969. default:
  61970. throw new Error("Invalid geometry type " + type);
  61971. }
  61972. if (!status.ok() || !geometry.ptr) {
  61973. throw new Error(status.error_msg());
  61974. }
  61975. var numPoints = geometry.num_points();
  61976. if (type === module.TRIANGULAR_MESH) {
  61977. var numFaces = geometry.num_faces();
  61978. var faceIndices = new module.DracoInt32Array();
  61979. try {
  61980. var indices = new Uint32Array(numFaces * 3);
  61981. for (var i = 0; i < numFaces; i++) {
  61982. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61983. var offset = i * 3;
  61984. indices[offset + 0] = faceIndices.GetValue(0);
  61985. indices[offset + 1] = faceIndices.GetValue(1);
  61986. indices[offset + 2] = faceIndices.GetValue(2);
  61987. }
  61988. vertexData.indices = indices;
  61989. }
  61990. finally {
  61991. module.destroy(faceIndices);
  61992. }
  61993. }
  61994. for (var kind in attributes) {
  61995. var uniqueId = attributes[kind];
  61996. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61997. var dracoData = new module.DracoFloat32Array();
  61998. try {
  61999. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62000. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62001. for (var i = 0; i < babylonData.length; i++) {
  62002. babylonData[i] = dracoData.GetValue(i);
  62003. }
  62004. vertexData.set(babylonData, kind);
  62005. }
  62006. finally {
  62007. module.destroy(dracoData);
  62008. }
  62009. }
  62010. }
  62011. finally {
  62012. if (geometry) {
  62013. module.destroy(geometry);
  62014. }
  62015. module.destroy(decoder);
  62016. module.destroy(buffer);
  62017. }
  62018. return vertexData;
  62019. });
  62020. };
  62021. DracoCompression._GetDecoderModule = function () {
  62022. if (!DracoCompression._DecoderModulePromise) {
  62023. var promise = null;
  62024. var config_1 = {};
  62025. if (typeof DracoDecoderModule !== "undefined") {
  62026. promise = Promise.resolve();
  62027. }
  62028. else {
  62029. var decoder = DracoCompression.Configuration.decoder;
  62030. if (decoder) {
  62031. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62032. promise = Promise.all([
  62033. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62034. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62035. config_1.wasmBinary = data;
  62036. })
  62037. ]);
  62038. }
  62039. else if (decoder.fallbackUrl) {
  62040. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62041. }
  62042. }
  62043. }
  62044. if (!promise) {
  62045. throw new Error("Draco decoder module is not available");
  62046. }
  62047. DracoCompression._DecoderModulePromise = promise.then(function () {
  62048. return new Promise(function (resolve) {
  62049. config_1.onModuleLoaded = function (decoderModule) {
  62050. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62051. resolve({ module: decoderModule });
  62052. };
  62053. DracoDecoderModule(config_1);
  62054. });
  62055. });
  62056. }
  62057. return DracoCompression._DecoderModulePromise;
  62058. };
  62059. DracoCompression._LoadScriptAsync = function (url) {
  62060. return new Promise(function (resolve, reject) {
  62061. BABYLON.Tools.LoadScript(url, function () {
  62062. resolve();
  62063. }, function (message) {
  62064. reject(new Error(message));
  62065. });
  62066. });
  62067. };
  62068. DracoCompression._LoadFileAsync = function (url) {
  62069. return new Promise(function (resolve, reject) {
  62070. BABYLON.Tools.LoadFile(url, function (data) {
  62071. resolve(data);
  62072. }, undefined, undefined, true, function (request, exception) {
  62073. reject(exception);
  62074. });
  62075. });
  62076. };
  62077. /**
  62078. * The configuration. Defaults to the following urls:
  62079. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62080. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62081. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62082. */
  62083. DracoCompression.Configuration = {
  62084. decoder: {
  62085. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62086. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62087. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62088. }
  62089. };
  62090. return DracoCompression;
  62091. }());
  62092. BABYLON.DracoCompression = DracoCompression;
  62093. })(BABYLON || (BABYLON = {}));
  62094. //# sourceMappingURL=babylon.dracoCompression.js.map
  62095. var BABYLON;
  62096. (function (BABYLON) {
  62097. var AudioEngine = /** @class */ (function () {
  62098. function AudioEngine() {
  62099. this._audioContext = null;
  62100. this._audioContextInitialized = false;
  62101. this.canUseWebAudio = false;
  62102. this.WarnedWebAudioUnsupported = false;
  62103. this.unlocked = false;
  62104. this.isMP3supported = false;
  62105. this.isOGGsupported = false;
  62106. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62107. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62108. this.canUseWebAudio = true;
  62109. }
  62110. var audioElem = document.createElement('audio');
  62111. try {
  62112. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62113. this.isMP3supported = true;
  62114. }
  62115. }
  62116. catch (e) {
  62117. // protect error during capability check.
  62118. }
  62119. try {
  62120. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62121. this.isOGGsupported = true;
  62122. }
  62123. }
  62124. catch (e) {
  62125. // protect error during capability check.
  62126. }
  62127. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62128. this._unlockiOSaudio();
  62129. }
  62130. else {
  62131. this.unlocked = true;
  62132. }
  62133. }
  62134. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62135. get: function () {
  62136. if (!this._audioContextInitialized) {
  62137. this._initializeAudioContext();
  62138. }
  62139. return this._audioContext;
  62140. },
  62141. enumerable: true,
  62142. configurable: true
  62143. });
  62144. AudioEngine.prototype._unlockiOSaudio = function () {
  62145. var _this = this;
  62146. var unlockaudio = function () {
  62147. if (!_this.audioContext) {
  62148. return;
  62149. }
  62150. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62151. var source = _this.audioContext.createBufferSource();
  62152. source.buffer = buffer;
  62153. source.connect(_this.audioContext.destination);
  62154. source.start(0);
  62155. setTimeout(function () {
  62156. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62157. _this.unlocked = true;
  62158. window.removeEventListener('touchend', unlockaudio, false);
  62159. if (_this.onAudioUnlocked) {
  62160. _this.onAudioUnlocked();
  62161. }
  62162. }
  62163. }, 0);
  62164. };
  62165. window.addEventListener('touchend', unlockaudio, false);
  62166. };
  62167. AudioEngine.prototype._initializeAudioContext = function () {
  62168. try {
  62169. if (this.canUseWebAudio) {
  62170. this._audioContext = new AudioContext();
  62171. // create a global volume gain node
  62172. this.masterGain = this._audioContext.createGain();
  62173. this.masterGain.gain.value = 1;
  62174. this.masterGain.connect(this._audioContext.destination);
  62175. this._audioContextInitialized = true;
  62176. }
  62177. }
  62178. catch (e) {
  62179. this.canUseWebAudio = false;
  62180. BABYLON.Tools.Error("Web Audio: " + e.message);
  62181. }
  62182. };
  62183. AudioEngine.prototype.dispose = function () {
  62184. if (this.canUseWebAudio && this._audioContextInitialized) {
  62185. if (this._connectedAnalyser && this._audioContext) {
  62186. this._connectedAnalyser.stopDebugCanvas();
  62187. this._connectedAnalyser.dispose();
  62188. this.masterGain.disconnect();
  62189. this.masterGain.connect(this._audioContext.destination);
  62190. this._connectedAnalyser = null;
  62191. }
  62192. this.masterGain.gain.value = 1;
  62193. }
  62194. this.WarnedWebAudioUnsupported = false;
  62195. };
  62196. AudioEngine.prototype.getGlobalVolume = function () {
  62197. if (this.canUseWebAudio && this._audioContextInitialized) {
  62198. return this.masterGain.gain.value;
  62199. }
  62200. else {
  62201. return -1;
  62202. }
  62203. };
  62204. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62205. if (this.canUseWebAudio && this._audioContextInitialized) {
  62206. this.masterGain.gain.value = newVolume;
  62207. }
  62208. };
  62209. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62210. if (this._connectedAnalyser) {
  62211. this._connectedAnalyser.stopDebugCanvas();
  62212. }
  62213. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62214. this._connectedAnalyser = analyser;
  62215. this.masterGain.disconnect();
  62216. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62217. }
  62218. };
  62219. return AudioEngine;
  62220. }());
  62221. BABYLON.AudioEngine = AudioEngine;
  62222. })(BABYLON || (BABYLON = {}));
  62223. //# sourceMappingURL=babylon.audioEngine.js.map
  62224. var BABYLON;
  62225. (function (BABYLON) {
  62226. var Sound = /** @class */ (function () {
  62227. /**
  62228. * Create a sound and attach it to a scene
  62229. * @param name Name of your sound
  62230. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62231. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62232. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62233. */
  62234. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62235. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62236. var _this = this;
  62237. this.autoplay = false;
  62238. this.loop = false;
  62239. this.useCustomAttenuation = false;
  62240. this.spatialSound = false;
  62241. this.refDistance = 1;
  62242. this.rolloffFactor = 1;
  62243. this.maxDistance = 100;
  62244. this.distanceModel = "linear";
  62245. this._panningModel = "equalpower";
  62246. this._playbackRate = 1;
  62247. this._streaming = false;
  62248. this._startTime = 0;
  62249. this._startOffset = 0;
  62250. this._position = BABYLON.Vector3.Zero();
  62251. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62252. this._volume = 1;
  62253. this._isReadyToPlay = false;
  62254. this.isPlaying = false;
  62255. this.isPaused = false;
  62256. this._isDirectional = false;
  62257. // Used if you'd like to create a directional sound.
  62258. // If not set, the sound will be omnidirectional
  62259. this._coneInnerAngle = 360;
  62260. this._coneOuterAngle = 360;
  62261. this._coneOuterGain = 0;
  62262. this._isOutputConnected = false;
  62263. this._urlType = "Unknown";
  62264. this.name = name;
  62265. this._scene = scene;
  62266. this._readyToPlayCallback = readyToPlayCallback;
  62267. // Default custom attenuation function is a linear attenuation
  62268. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62269. if (currentDistance < maxDistance) {
  62270. return currentVolume * (1 - currentDistance / maxDistance);
  62271. }
  62272. else {
  62273. return 0;
  62274. }
  62275. };
  62276. if (options) {
  62277. this.autoplay = options.autoplay || false;
  62278. this.loop = options.loop || false;
  62279. // if volume === 0, we need another way to check this option
  62280. if (options.volume !== undefined) {
  62281. this._volume = options.volume;
  62282. }
  62283. this.spatialSound = options.spatialSound || false;
  62284. this.maxDistance = options.maxDistance || 100;
  62285. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62286. this.rolloffFactor = options.rolloffFactor || 1;
  62287. this.refDistance = options.refDistance || 1;
  62288. this.distanceModel = options.distanceModel || "linear";
  62289. this._playbackRate = options.playbackRate || 1;
  62290. this._streaming = options.streaming || false;
  62291. }
  62292. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62293. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62294. this._soundGain.gain.value = this._volume;
  62295. this._inputAudioNode = this._soundGain;
  62296. this._ouputAudioNode = this._soundGain;
  62297. if (this.spatialSound) {
  62298. this._createSpatialParameters();
  62299. }
  62300. this._scene.mainSoundTrack.AddSound(this);
  62301. var validParameter = true;
  62302. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62303. if (urlOrArrayBuffer) {
  62304. try {
  62305. if (typeof (urlOrArrayBuffer) === "string") {
  62306. this._urlType = "String";
  62307. }
  62308. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62309. this._urlType = "ArrayBuffer";
  62310. }
  62311. else if (urlOrArrayBuffer instanceof MediaStream) {
  62312. this._urlType = "MediaStream";
  62313. }
  62314. else if (Array.isArray(urlOrArrayBuffer)) {
  62315. this._urlType = "Array";
  62316. }
  62317. var urls = [];
  62318. var codecSupportedFound = false;
  62319. switch (this._urlType) {
  62320. case "MediaStream":
  62321. this._streaming = true;
  62322. this._isReadyToPlay = true;
  62323. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62324. if (this.autoplay) {
  62325. this.play();
  62326. }
  62327. if (this._readyToPlayCallback) {
  62328. this._readyToPlayCallback();
  62329. }
  62330. break;
  62331. case "ArrayBuffer":
  62332. if (urlOrArrayBuffer.byteLength > 0) {
  62333. codecSupportedFound = true;
  62334. this._soundLoaded(urlOrArrayBuffer);
  62335. }
  62336. break;
  62337. case "String":
  62338. urls.push(urlOrArrayBuffer);
  62339. case "Array":
  62340. if (urls.length === 0)
  62341. urls = urlOrArrayBuffer;
  62342. // If we found a supported format, we load it immediately and stop the loop
  62343. for (var i = 0; i < urls.length; i++) {
  62344. var url = urls[i];
  62345. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62346. codecSupportedFound = true;
  62347. }
  62348. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62349. codecSupportedFound = true;
  62350. }
  62351. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62352. codecSupportedFound = true;
  62353. }
  62354. if (url.indexOf("blob:") !== -1) {
  62355. codecSupportedFound = true;
  62356. }
  62357. if (codecSupportedFound) {
  62358. // Loading sound using XHR2
  62359. if (!this._streaming) {
  62360. this._scene._loadFile(url, function (data) {
  62361. _this._soundLoaded(data);
  62362. }, undefined, true, true, function (exception) {
  62363. if (exception) {
  62364. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62365. }
  62366. BABYLON.Tools.Error("Sound creation aborted.");
  62367. _this._scene.mainSoundTrack.RemoveSound(_this);
  62368. });
  62369. }
  62370. // Streaming sound using HTML5 Audio tag
  62371. else {
  62372. this._htmlAudioElement = new Audio(url);
  62373. this._htmlAudioElement.controls = false;
  62374. this._htmlAudioElement.loop = this.loop;
  62375. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62376. this._htmlAudioElement.preload = "auto";
  62377. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62378. _this._isReadyToPlay = true;
  62379. if (_this.autoplay) {
  62380. _this.play();
  62381. }
  62382. if (_this._readyToPlayCallback) {
  62383. _this._readyToPlayCallback();
  62384. }
  62385. });
  62386. document.body.appendChild(this._htmlAudioElement);
  62387. }
  62388. break;
  62389. }
  62390. }
  62391. break;
  62392. default:
  62393. validParameter = false;
  62394. break;
  62395. }
  62396. if (!validParameter) {
  62397. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62398. }
  62399. else {
  62400. if (!codecSupportedFound) {
  62401. this._isReadyToPlay = true;
  62402. // Simulating a ready to play event to avoid breaking code path
  62403. if (this._readyToPlayCallback) {
  62404. window.setTimeout(function () {
  62405. if (_this._readyToPlayCallback) {
  62406. _this._readyToPlayCallback();
  62407. }
  62408. }, 1000);
  62409. }
  62410. }
  62411. }
  62412. }
  62413. catch (ex) {
  62414. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62415. this._scene.mainSoundTrack.RemoveSound(this);
  62416. }
  62417. }
  62418. }
  62419. else {
  62420. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62421. this._scene.mainSoundTrack.AddSound(this);
  62422. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62423. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62424. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62425. }
  62426. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62427. if (this._readyToPlayCallback) {
  62428. window.setTimeout(function () {
  62429. if (_this._readyToPlayCallback) {
  62430. _this._readyToPlayCallback();
  62431. }
  62432. }, 1000);
  62433. }
  62434. }
  62435. }
  62436. Sound.prototype.dispose = function () {
  62437. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62438. if (this.isPlaying) {
  62439. this.stop();
  62440. }
  62441. this._isReadyToPlay = false;
  62442. if (this.soundTrackId === -1) {
  62443. this._scene.mainSoundTrack.RemoveSound(this);
  62444. }
  62445. else {
  62446. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62447. }
  62448. if (this._soundGain) {
  62449. this._soundGain.disconnect();
  62450. this._soundGain = null;
  62451. }
  62452. if (this._soundPanner) {
  62453. this._soundPanner.disconnect();
  62454. this._soundPanner = null;
  62455. }
  62456. if (this._soundSource) {
  62457. this._soundSource.disconnect();
  62458. this._soundSource = null;
  62459. }
  62460. this._audioBuffer = null;
  62461. if (this._htmlAudioElement) {
  62462. this._htmlAudioElement.pause();
  62463. this._htmlAudioElement.src = "";
  62464. document.body.removeChild(this._htmlAudioElement);
  62465. }
  62466. if (this._streamingSource) {
  62467. this._streamingSource.disconnect();
  62468. }
  62469. if (this._connectedMesh && this._registerFunc) {
  62470. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62471. this._connectedMesh = null;
  62472. }
  62473. }
  62474. };
  62475. Sound.prototype.isReady = function () {
  62476. return this._isReadyToPlay;
  62477. };
  62478. Sound.prototype._soundLoaded = function (audioData) {
  62479. var _this = this;
  62480. if (!BABYLON.Engine.audioEngine.audioContext) {
  62481. return;
  62482. }
  62483. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62484. _this._audioBuffer = buffer;
  62485. _this._isReadyToPlay = true;
  62486. if (_this.autoplay) {
  62487. _this.play();
  62488. }
  62489. if (_this._readyToPlayCallback) {
  62490. _this._readyToPlayCallback();
  62491. }
  62492. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62493. };
  62494. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62495. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62496. this._audioBuffer = audioBuffer;
  62497. this._isReadyToPlay = true;
  62498. }
  62499. };
  62500. Sound.prototype.updateOptions = function (options) {
  62501. if (options) {
  62502. this.loop = options.loop || this.loop;
  62503. this.maxDistance = options.maxDistance || this.maxDistance;
  62504. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62505. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62506. this.refDistance = options.refDistance || this.refDistance;
  62507. this.distanceModel = options.distanceModel || this.distanceModel;
  62508. this._playbackRate = options.playbackRate || this._playbackRate;
  62509. this._updateSpatialParameters();
  62510. if (this.isPlaying) {
  62511. if (this._streaming && this._htmlAudioElement) {
  62512. this._htmlAudioElement.playbackRate = this._playbackRate;
  62513. }
  62514. else {
  62515. if (this._soundSource) {
  62516. this._soundSource.playbackRate.value = this._playbackRate;
  62517. }
  62518. }
  62519. }
  62520. }
  62521. };
  62522. Sound.prototype._createSpatialParameters = function () {
  62523. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62524. if (this._scene.headphone) {
  62525. this._panningModel = "HRTF";
  62526. }
  62527. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62528. this._updateSpatialParameters();
  62529. this._soundPanner.connect(this._ouputAudioNode);
  62530. this._inputAudioNode = this._soundPanner;
  62531. }
  62532. };
  62533. Sound.prototype._updateSpatialParameters = function () {
  62534. if (this.spatialSound && this._soundPanner) {
  62535. if (this.useCustomAttenuation) {
  62536. // Tricks to disable in a way embedded Web Audio attenuation
  62537. this._soundPanner.distanceModel = "linear";
  62538. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62539. this._soundPanner.refDistance = 1;
  62540. this._soundPanner.rolloffFactor = 1;
  62541. this._soundPanner.panningModel = this._panningModel;
  62542. }
  62543. else {
  62544. this._soundPanner.distanceModel = this.distanceModel;
  62545. this._soundPanner.maxDistance = this.maxDistance;
  62546. this._soundPanner.refDistance = this.refDistance;
  62547. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62548. this._soundPanner.panningModel = this._panningModel;
  62549. }
  62550. }
  62551. };
  62552. Sound.prototype.switchPanningModelToHRTF = function () {
  62553. this._panningModel = "HRTF";
  62554. this._switchPanningModel();
  62555. };
  62556. Sound.prototype.switchPanningModelToEqualPower = function () {
  62557. this._panningModel = "equalpower";
  62558. this._switchPanningModel();
  62559. };
  62560. Sound.prototype._switchPanningModel = function () {
  62561. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62562. this._soundPanner.panningModel = this._panningModel;
  62563. }
  62564. };
  62565. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62566. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62567. if (this._isOutputConnected) {
  62568. this._ouputAudioNode.disconnect();
  62569. }
  62570. this._ouputAudioNode.connect(soundTrackAudioNode);
  62571. this._isOutputConnected = true;
  62572. }
  62573. };
  62574. /**
  62575. * Transform this sound into a directional source
  62576. * @param coneInnerAngle Size of the inner cone in degree
  62577. * @param coneOuterAngle Size of the outer cone in degree
  62578. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62579. */
  62580. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62581. if (coneOuterAngle < coneInnerAngle) {
  62582. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62583. return;
  62584. }
  62585. this._coneInnerAngle = coneInnerAngle;
  62586. this._coneOuterAngle = coneOuterAngle;
  62587. this._coneOuterGain = coneOuterGain;
  62588. this._isDirectional = true;
  62589. if (this.isPlaying && this.loop) {
  62590. this.stop();
  62591. this.play();
  62592. }
  62593. };
  62594. Sound.prototype.setPosition = function (newPosition) {
  62595. this._position = newPosition;
  62596. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62597. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62598. }
  62599. };
  62600. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62601. this._localDirection = newLocalDirection;
  62602. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62603. this._updateDirection();
  62604. }
  62605. };
  62606. Sound.prototype._updateDirection = function () {
  62607. if (!this._connectedMesh || !this._soundPanner) {
  62608. return;
  62609. }
  62610. var mat = this._connectedMesh.getWorldMatrix();
  62611. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62612. direction.normalize();
  62613. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62614. };
  62615. Sound.prototype.updateDistanceFromListener = function () {
  62616. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62617. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62618. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62619. }
  62620. };
  62621. Sound.prototype.setAttenuationFunction = function (callback) {
  62622. this._customAttenuationFunction = callback;
  62623. };
  62624. /**
  62625. * Play the sound
  62626. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62627. * @param offset (optional) Start the sound setting it at a specific time
  62628. */
  62629. Sound.prototype.play = function (time, offset) {
  62630. var _this = this;
  62631. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62632. try {
  62633. if (this._startOffset < 0) {
  62634. time = -this._startOffset;
  62635. this._startOffset = 0;
  62636. }
  62637. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62638. if (!this._soundSource || !this._streamingSource) {
  62639. if (this.spatialSound && this._soundPanner) {
  62640. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62641. if (this._isDirectional) {
  62642. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62643. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62644. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62645. if (this._connectedMesh) {
  62646. this._updateDirection();
  62647. }
  62648. else {
  62649. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62650. }
  62651. }
  62652. }
  62653. }
  62654. if (this._streaming) {
  62655. if (!this._streamingSource) {
  62656. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62657. this._htmlAudioElement.onended = function () { _this._onended(); };
  62658. this._htmlAudioElement.playbackRate = this._playbackRate;
  62659. }
  62660. this._streamingSource.disconnect();
  62661. this._streamingSource.connect(this._inputAudioNode);
  62662. if (this._htmlAudioElement) {
  62663. this._htmlAudioElement.play();
  62664. }
  62665. }
  62666. else {
  62667. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62668. this._soundSource.buffer = this._audioBuffer;
  62669. this._soundSource.connect(this._inputAudioNode);
  62670. this._soundSource.loop = this.loop;
  62671. this._soundSource.playbackRate.value = this._playbackRate;
  62672. this._soundSource.onended = function () { _this._onended(); };
  62673. if (this._soundSource.buffer) {
  62674. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62675. }
  62676. }
  62677. this._startTime = startTime;
  62678. this.isPlaying = true;
  62679. this.isPaused = false;
  62680. }
  62681. catch (ex) {
  62682. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62683. }
  62684. }
  62685. };
  62686. Sound.prototype._onended = function () {
  62687. this.isPlaying = false;
  62688. if (this.onended) {
  62689. this.onended();
  62690. }
  62691. };
  62692. /**
  62693. * Stop the sound
  62694. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62695. */
  62696. Sound.prototype.stop = function (time) {
  62697. if (this.isPlaying) {
  62698. if (this._streaming) {
  62699. if (this._htmlAudioElement) {
  62700. this._htmlAudioElement.pause();
  62701. // Test needed for Firefox or it will generate an Invalid State Error
  62702. if (this._htmlAudioElement.currentTime > 0) {
  62703. this._htmlAudioElement.currentTime = 0;
  62704. }
  62705. }
  62706. else {
  62707. this._streamingSource.disconnect();
  62708. }
  62709. }
  62710. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62711. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62712. this._soundSource.stop(stopTime);
  62713. this._soundSource.onended = function () { };
  62714. if (!this.isPaused) {
  62715. this._startOffset = 0;
  62716. }
  62717. }
  62718. this.isPlaying = false;
  62719. }
  62720. };
  62721. Sound.prototype.pause = function () {
  62722. if (this.isPlaying) {
  62723. this.isPaused = true;
  62724. if (this._streaming) {
  62725. if (this._htmlAudioElement) {
  62726. this._htmlAudioElement.pause();
  62727. }
  62728. else {
  62729. this._streamingSource.disconnect();
  62730. }
  62731. }
  62732. else if (BABYLON.Engine.audioEngine.audioContext) {
  62733. this.stop(0);
  62734. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62735. }
  62736. }
  62737. };
  62738. Sound.prototype.setVolume = function (newVolume, time) {
  62739. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62740. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62741. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62742. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62743. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62744. }
  62745. else {
  62746. this._soundGain.gain.value = newVolume;
  62747. }
  62748. }
  62749. this._volume = newVolume;
  62750. };
  62751. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62752. this._playbackRate = newPlaybackRate;
  62753. if (this.isPlaying) {
  62754. if (this._streaming && this._htmlAudioElement) {
  62755. this._htmlAudioElement.playbackRate = this._playbackRate;
  62756. }
  62757. else if (this._soundSource) {
  62758. this._soundSource.playbackRate.value = this._playbackRate;
  62759. }
  62760. }
  62761. };
  62762. Sound.prototype.getVolume = function () {
  62763. return this._volume;
  62764. };
  62765. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62766. var _this = this;
  62767. if (this._connectedMesh && this._registerFunc) {
  62768. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62769. this._registerFunc = null;
  62770. }
  62771. this._connectedMesh = meshToConnectTo;
  62772. if (!this.spatialSound) {
  62773. this.spatialSound = true;
  62774. this._createSpatialParameters();
  62775. if (this.isPlaying && this.loop) {
  62776. this.stop();
  62777. this.play();
  62778. }
  62779. }
  62780. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62781. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62782. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62783. };
  62784. Sound.prototype.detachFromMesh = function () {
  62785. if (this._connectedMesh && this._registerFunc) {
  62786. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62787. this._registerFunc = null;
  62788. this._connectedMesh = null;
  62789. }
  62790. };
  62791. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62792. if (!node.getBoundingInfo) {
  62793. return;
  62794. }
  62795. var mesh = node;
  62796. var boundingInfo = mesh.getBoundingInfo();
  62797. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62798. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62799. this._updateDirection();
  62800. }
  62801. };
  62802. Sound.prototype.clone = function () {
  62803. var _this = this;
  62804. if (!this._streaming) {
  62805. var setBufferAndRun = function () {
  62806. if (_this._isReadyToPlay) {
  62807. clonedSound._audioBuffer = _this.getAudioBuffer();
  62808. clonedSound._isReadyToPlay = true;
  62809. if (clonedSound.autoplay) {
  62810. clonedSound.play();
  62811. }
  62812. }
  62813. else {
  62814. window.setTimeout(setBufferAndRun, 300);
  62815. }
  62816. };
  62817. var currentOptions = {
  62818. autoplay: this.autoplay, loop: this.loop,
  62819. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62820. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62821. refDistance: this.refDistance, distanceModel: this.distanceModel
  62822. };
  62823. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62824. if (this.useCustomAttenuation) {
  62825. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62826. }
  62827. clonedSound.setPosition(this._position);
  62828. clonedSound.setPlaybackRate(this._playbackRate);
  62829. setBufferAndRun();
  62830. return clonedSound;
  62831. }
  62832. // Can't clone a streaming sound
  62833. else {
  62834. return null;
  62835. }
  62836. };
  62837. Sound.prototype.getAudioBuffer = function () {
  62838. return this._audioBuffer;
  62839. };
  62840. Sound.prototype.serialize = function () {
  62841. var serializationObject = {
  62842. name: this.name,
  62843. url: this.name,
  62844. autoplay: this.autoplay,
  62845. loop: this.loop,
  62846. volume: this._volume,
  62847. spatialSound: this.spatialSound,
  62848. maxDistance: this.maxDistance,
  62849. rolloffFactor: this.rolloffFactor,
  62850. refDistance: this.refDistance,
  62851. distanceModel: this.distanceModel,
  62852. playbackRate: this._playbackRate,
  62853. panningModel: this._panningModel,
  62854. soundTrackId: this.soundTrackId
  62855. };
  62856. if (this.spatialSound) {
  62857. if (this._connectedMesh)
  62858. serializationObject.connectedMeshId = this._connectedMesh.id;
  62859. serializationObject.position = this._position.asArray();
  62860. serializationObject.refDistance = this.refDistance;
  62861. serializationObject.distanceModel = this.distanceModel;
  62862. serializationObject.isDirectional = this._isDirectional;
  62863. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62864. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62865. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62866. serializationObject.coneOuterGain = this._coneOuterGain;
  62867. }
  62868. return serializationObject;
  62869. };
  62870. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62871. var soundName = parsedSound.name;
  62872. var soundUrl;
  62873. if (parsedSound.url) {
  62874. soundUrl = rootUrl + parsedSound.url;
  62875. }
  62876. else {
  62877. soundUrl = rootUrl + soundName;
  62878. }
  62879. var options = {
  62880. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62881. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62882. rolloffFactor: parsedSound.rolloffFactor,
  62883. refDistance: parsedSound.refDistance,
  62884. distanceModel: parsedSound.distanceModel,
  62885. playbackRate: parsedSound.playbackRate
  62886. };
  62887. var newSound;
  62888. if (!sourceSound) {
  62889. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62890. scene._addPendingData(newSound);
  62891. }
  62892. else {
  62893. var setBufferAndRun = function () {
  62894. if (sourceSound._isReadyToPlay) {
  62895. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62896. newSound._isReadyToPlay = true;
  62897. if (newSound.autoplay) {
  62898. newSound.play();
  62899. }
  62900. }
  62901. else {
  62902. window.setTimeout(setBufferAndRun, 300);
  62903. }
  62904. };
  62905. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62906. setBufferAndRun();
  62907. }
  62908. if (parsedSound.position) {
  62909. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62910. newSound.setPosition(soundPosition);
  62911. }
  62912. if (parsedSound.isDirectional) {
  62913. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62914. if (parsedSound.localDirectionToMesh) {
  62915. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62916. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62917. }
  62918. }
  62919. if (parsedSound.connectedMeshId) {
  62920. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62921. if (connectedMesh) {
  62922. newSound.attachToMesh(connectedMesh);
  62923. }
  62924. }
  62925. return newSound;
  62926. };
  62927. return Sound;
  62928. }());
  62929. BABYLON.Sound = Sound;
  62930. })(BABYLON || (BABYLON = {}));
  62931. //# sourceMappingURL=babylon.sound.js.map
  62932. var BABYLON;
  62933. (function (BABYLON) {
  62934. var SoundTrack = /** @class */ (function () {
  62935. function SoundTrack(scene, options) {
  62936. this.id = -1;
  62937. this._isMainTrack = false;
  62938. this._isInitialized = false;
  62939. this._scene = scene;
  62940. this.soundCollection = new Array();
  62941. this._options = options;
  62942. if (!this._isMainTrack) {
  62943. this._scene.soundTracks.push(this);
  62944. this.id = this._scene.soundTracks.length - 1;
  62945. }
  62946. }
  62947. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62948. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62949. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62950. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62951. if (this._options) {
  62952. if (this._options.volume) {
  62953. this._outputAudioNode.gain.value = this._options.volume;
  62954. }
  62955. if (this._options.mainTrack) {
  62956. this._isMainTrack = this._options.mainTrack;
  62957. }
  62958. }
  62959. this._isInitialized = true;
  62960. }
  62961. };
  62962. SoundTrack.prototype.dispose = function () {
  62963. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62964. if (this._connectedAnalyser) {
  62965. this._connectedAnalyser.stopDebugCanvas();
  62966. }
  62967. while (this.soundCollection.length) {
  62968. this.soundCollection[0].dispose();
  62969. }
  62970. if (this._outputAudioNode) {
  62971. this._outputAudioNode.disconnect();
  62972. }
  62973. this._outputAudioNode = null;
  62974. }
  62975. };
  62976. SoundTrack.prototype.AddSound = function (sound) {
  62977. if (!this._isInitialized) {
  62978. this._initializeSoundTrackAudioGraph();
  62979. }
  62980. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62981. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62982. }
  62983. if (sound.soundTrackId) {
  62984. if (sound.soundTrackId === -1) {
  62985. this._scene.mainSoundTrack.RemoveSound(sound);
  62986. }
  62987. else {
  62988. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62989. }
  62990. }
  62991. this.soundCollection.push(sound);
  62992. sound.soundTrackId = this.id;
  62993. };
  62994. SoundTrack.prototype.RemoveSound = function (sound) {
  62995. var index = this.soundCollection.indexOf(sound);
  62996. if (index !== -1) {
  62997. this.soundCollection.splice(index, 1);
  62998. }
  62999. };
  63000. SoundTrack.prototype.setVolume = function (newVolume) {
  63001. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63002. this._outputAudioNode.gain.value = newVolume;
  63003. }
  63004. };
  63005. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63006. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63007. for (var i = 0; i < this.soundCollection.length; i++) {
  63008. this.soundCollection[i].switchPanningModelToHRTF();
  63009. }
  63010. }
  63011. };
  63012. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63013. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63014. for (var i = 0; i < this.soundCollection.length; i++) {
  63015. this.soundCollection[i].switchPanningModelToEqualPower();
  63016. }
  63017. }
  63018. };
  63019. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63020. if (this._connectedAnalyser) {
  63021. this._connectedAnalyser.stopDebugCanvas();
  63022. }
  63023. this._connectedAnalyser = analyser;
  63024. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63025. this._outputAudioNode.disconnect();
  63026. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63027. }
  63028. };
  63029. return SoundTrack;
  63030. }());
  63031. BABYLON.SoundTrack = SoundTrack;
  63032. })(BABYLON || (BABYLON = {}));
  63033. //# sourceMappingURL=babylon.soundtrack.js.map
  63034. var BABYLON;
  63035. (function (BABYLON) {
  63036. /**
  63037. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63038. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63039. */
  63040. var Analyser = /** @class */ (function () {
  63041. /**
  63042. * Creates a new analyser
  63043. * @param scene defines hosting scene
  63044. */
  63045. function Analyser(scene) {
  63046. /**
  63047. * Gets or sets the smoothing
  63048. * @ignorenaming
  63049. */
  63050. this.SMOOTHING = 0.75;
  63051. /**
  63052. * Gets or sets the FFT table size
  63053. * @ignorenaming
  63054. */
  63055. this.FFT_SIZE = 512;
  63056. /**
  63057. * Gets or sets the bar graph amplitude
  63058. * @ignorenaming
  63059. */
  63060. this.BARGRAPHAMPLITUDE = 256;
  63061. /**
  63062. * Gets or sets the position of the debug canvas
  63063. * @ignorenaming
  63064. */
  63065. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63066. /**
  63067. * Gets or sets the debug canvas size
  63068. * @ignorenaming
  63069. */
  63070. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63071. this._scene = scene;
  63072. this._audioEngine = BABYLON.Engine.audioEngine;
  63073. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63074. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63075. this._webAudioAnalyser.minDecibels = -140;
  63076. this._webAudioAnalyser.maxDecibels = 0;
  63077. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63078. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63079. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63080. }
  63081. }
  63082. /**
  63083. * Get the number of data values you will have to play with for the visualization
  63084. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63085. * @returns a number
  63086. */
  63087. Analyser.prototype.getFrequencyBinCount = function () {
  63088. if (this._audioEngine.canUseWebAudio) {
  63089. return this._webAudioAnalyser.frequencyBinCount;
  63090. }
  63091. else {
  63092. return 0;
  63093. }
  63094. };
  63095. /**
  63096. * Gets the current frequency data as a byte array
  63097. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63098. * @returns a Uint8Array
  63099. */
  63100. Analyser.prototype.getByteFrequencyData = function () {
  63101. if (this._audioEngine.canUseWebAudio) {
  63102. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63103. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63104. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63105. }
  63106. return this._byteFreqs;
  63107. };
  63108. /**
  63109. * Gets the current waveform as a byte array
  63110. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63111. * @returns a Uint8Array
  63112. */
  63113. Analyser.prototype.getByteTimeDomainData = function () {
  63114. if (this._audioEngine.canUseWebAudio) {
  63115. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63116. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63117. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63118. }
  63119. return this._byteTime;
  63120. };
  63121. /**
  63122. * Gets the current frequency data as a float array
  63123. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63124. * @returns a Float32Array
  63125. */
  63126. Analyser.prototype.getFloatFrequencyData = function () {
  63127. if (this._audioEngine.canUseWebAudio) {
  63128. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63129. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63130. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63131. }
  63132. return this._floatFreqs;
  63133. };
  63134. /**
  63135. * Renders the debug canvas
  63136. */
  63137. Analyser.prototype.drawDebugCanvas = function () {
  63138. var _this = this;
  63139. if (this._audioEngine.canUseWebAudio) {
  63140. if (!this._debugCanvas) {
  63141. this._debugCanvas = document.createElement("canvas");
  63142. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63143. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63144. this._debugCanvas.style.position = "absolute";
  63145. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63146. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63147. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63148. document.body.appendChild(this._debugCanvas);
  63149. this._registerFunc = function () {
  63150. _this.drawDebugCanvas();
  63151. };
  63152. this._scene.registerBeforeRender(this._registerFunc);
  63153. }
  63154. if (this._registerFunc && this._debugCanvasContext) {
  63155. var workingArray = this.getByteFrequencyData();
  63156. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63157. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63158. // Draw the frequency domain chart.
  63159. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63160. var value = workingArray[i];
  63161. var percent = value / this.BARGRAPHAMPLITUDE;
  63162. var height = this.DEBUGCANVASSIZE.height * percent;
  63163. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63164. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63165. var hue = i / this.getFrequencyBinCount() * 360;
  63166. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63167. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63168. }
  63169. }
  63170. }
  63171. };
  63172. /**
  63173. * Stops rendering the debug canvas and removes it
  63174. */
  63175. Analyser.prototype.stopDebugCanvas = function () {
  63176. if (this._debugCanvas) {
  63177. if (this._registerFunc) {
  63178. this._scene.unregisterBeforeRender(this._registerFunc);
  63179. this._registerFunc = null;
  63180. }
  63181. document.body.removeChild(this._debugCanvas);
  63182. this._debugCanvas = null;
  63183. this._debugCanvasContext = null;
  63184. }
  63185. };
  63186. /**
  63187. * Connects two audio nodes
  63188. * @param inputAudioNode defines first node to connect
  63189. * @param outputAudioNode defines second node to connect
  63190. */
  63191. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63192. if (this._audioEngine.canUseWebAudio) {
  63193. inputAudioNode.connect(this._webAudioAnalyser);
  63194. this._webAudioAnalyser.connect(outputAudioNode);
  63195. }
  63196. };
  63197. /**
  63198. * Releases all associated resources
  63199. */
  63200. Analyser.prototype.dispose = function () {
  63201. if (this._audioEngine.canUseWebAudio) {
  63202. this._webAudioAnalyser.disconnect();
  63203. }
  63204. };
  63205. return Analyser;
  63206. }());
  63207. BABYLON.Analyser = Analyser;
  63208. })(BABYLON || (BABYLON = {}));
  63209. //# sourceMappingURL=babylon.analyser.js.map
  63210. var BABYLON;
  63211. (function (BABYLON) {
  63212. var CubeTexture = /** @class */ (function (_super) {
  63213. __extends(CubeTexture, _super);
  63214. /**
  63215. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63216. * as prefiltered data.
  63217. * @param rootUrl defines the url of the texture or the root name of the six images
  63218. * @param scene defines the scene the texture is attached to
  63219. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63220. * @param noMipmap defines if mipmaps should be created or not
  63221. * @param files defines the six files to load for the different faces
  63222. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63223. * @param onError defines a callback triggered in case of error during load
  63224. * @param format defines the internal format to use for the texture once loaded
  63225. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63226. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63227. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63228. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63229. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63230. * @return the cube texture
  63231. */
  63232. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63233. if (extensions === void 0) { extensions = null; }
  63234. if (noMipmap === void 0) { noMipmap = false; }
  63235. if (files === void 0) { files = null; }
  63236. if (onLoad === void 0) { onLoad = null; }
  63237. if (onError === void 0) { onError = null; }
  63238. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63239. if (prefiltered === void 0) { prefiltered = false; }
  63240. if (forcedExtension === void 0) { forcedExtension = null; }
  63241. if (createPolynomials === void 0) { createPolynomials = false; }
  63242. if (lodScale === void 0) { lodScale = 0.8; }
  63243. if (lodOffset === void 0) { lodOffset = 0; }
  63244. var _this = _super.call(this, scene) || this;
  63245. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63246. /**
  63247. * Gets or sets the center of the bounding box associated with the cube texture
  63248. * It must define where the camera used to render the texture was set
  63249. */
  63250. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63251. _this._rotationY = 0;
  63252. /** @hidden */
  63253. _this._prefiltered = false;
  63254. _this.name = rootUrl;
  63255. _this.url = rootUrl;
  63256. _this._noMipmap = noMipmap;
  63257. _this.hasAlpha = false;
  63258. _this._format = format;
  63259. _this.isCube = true;
  63260. _this._textureMatrix = BABYLON.Matrix.Identity();
  63261. _this._createPolynomials = createPolynomials;
  63262. if (!rootUrl && !files) {
  63263. return _this;
  63264. }
  63265. var lastDot = rootUrl.lastIndexOf(".");
  63266. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63267. var isDDS = (extension === ".dds");
  63268. var isEnv = (extension === ".env");
  63269. if (isEnv) {
  63270. _this.gammaSpace = false;
  63271. _this._prefiltered = false;
  63272. }
  63273. else {
  63274. _this._prefiltered = prefiltered;
  63275. if (prefiltered) {
  63276. _this.gammaSpace = false;
  63277. }
  63278. }
  63279. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63280. if (!files) {
  63281. if (!isEnv && !isDDS && !extensions) {
  63282. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63283. }
  63284. files = [];
  63285. if (extensions) {
  63286. for (var index = 0; index < extensions.length; index++) {
  63287. files.push(rootUrl + extensions[index]);
  63288. }
  63289. }
  63290. }
  63291. _this._files = files;
  63292. if (!_this._texture) {
  63293. if (!scene.useDelayedTextureLoading) {
  63294. if (prefiltered) {
  63295. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63296. }
  63297. else {
  63298. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63299. }
  63300. }
  63301. else {
  63302. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63303. }
  63304. }
  63305. else if (onLoad) {
  63306. if (_this._texture.isReady) {
  63307. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63308. }
  63309. else {
  63310. _this._texture.onLoadedObservable.add(onLoad);
  63311. }
  63312. }
  63313. return _this;
  63314. }
  63315. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63316. get: function () {
  63317. return this._boundingBoxSize;
  63318. },
  63319. /**
  63320. * Gets or sets the size of the bounding box associated with the cube texture
  63321. * When defined, the cubemap will switch to local mode
  63322. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63323. * @example https://www.babylonjs-playground.com/#RNASML
  63324. */
  63325. set: function (value) {
  63326. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63327. return;
  63328. }
  63329. this._boundingBoxSize = value;
  63330. var scene = this.getScene();
  63331. if (scene) {
  63332. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63333. }
  63334. },
  63335. enumerable: true,
  63336. configurable: true
  63337. });
  63338. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63339. /**
  63340. * Gets texture matrix rotation angle around Y axis radians.
  63341. */
  63342. get: function () {
  63343. return this._rotationY;
  63344. },
  63345. /**
  63346. * Sets texture matrix rotation angle around Y axis in radians.
  63347. */
  63348. set: function (value) {
  63349. this._rotationY = value;
  63350. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63351. },
  63352. enumerable: true,
  63353. configurable: true
  63354. });
  63355. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63356. var rootUrlKey = "";
  63357. files.forEach(function (url) { return rootUrlKey += url; });
  63358. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63359. };
  63360. /**
  63361. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63362. * @param url defines the url of the prefiltered texture
  63363. * @param scene defines the scene the texture is attached to
  63364. * @param forcedExtension defines the extension of the file if different from the url
  63365. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63366. * @return the prefiltered texture
  63367. */
  63368. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63369. if (forcedExtension === void 0) { forcedExtension = null; }
  63370. if (createPolynomials === void 0) { createPolynomials = true; }
  63371. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63372. };
  63373. // Methods
  63374. CubeTexture.prototype.delayLoad = function () {
  63375. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63376. return;
  63377. }
  63378. var scene = this.getScene();
  63379. if (!scene) {
  63380. return;
  63381. }
  63382. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63383. this._texture = this._getFromCache(this.url, this._noMipmap);
  63384. if (!this._texture) {
  63385. if (this._prefiltered) {
  63386. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63387. }
  63388. else {
  63389. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63390. }
  63391. }
  63392. };
  63393. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63394. return this._textureMatrix;
  63395. };
  63396. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63397. this._textureMatrix = value;
  63398. };
  63399. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63400. var texture = BABYLON.SerializationHelper.Parse(function () {
  63401. var prefiltered = false;
  63402. if (parsedTexture.prefiltered) {
  63403. prefiltered = parsedTexture.prefiltered;
  63404. }
  63405. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63406. }, parsedTexture, scene);
  63407. // Local Cubemaps
  63408. if (parsedTexture.boundingBoxPosition) {
  63409. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63410. }
  63411. if (parsedTexture.boundingBoxSize) {
  63412. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63413. }
  63414. // Animations
  63415. if (parsedTexture.animations) {
  63416. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63417. var parsedAnimation = parsedTexture.animations[animationIndex];
  63418. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63419. }
  63420. }
  63421. return texture;
  63422. };
  63423. CubeTexture.prototype.clone = function () {
  63424. var _this = this;
  63425. return BABYLON.SerializationHelper.Clone(function () {
  63426. var scene = _this.getScene();
  63427. if (!scene) {
  63428. return _this;
  63429. }
  63430. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63431. }, this);
  63432. };
  63433. __decorate([
  63434. BABYLON.serialize("rotationY")
  63435. ], CubeTexture.prototype, "_rotationY", void 0);
  63436. return CubeTexture;
  63437. }(BABYLON.BaseTexture));
  63438. BABYLON.CubeTexture = CubeTexture;
  63439. })(BABYLON || (BABYLON = {}));
  63440. //# sourceMappingURL=babylon.cubeTexture.js.map
  63441. var BABYLON;
  63442. (function (BABYLON) {
  63443. var RenderTargetTexture = /** @class */ (function (_super) {
  63444. __extends(RenderTargetTexture, _super);
  63445. /**
  63446. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63447. * or used a shadow, depth texture...
  63448. * @param name The friendly name of the texture
  63449. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  63450. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63451. * @param generateMipMaps True if mip maps need to be generated after render.
  63452. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63453. * @param type The type of the buffer in the RTT (int, half float, float...)
  63454. * @param isCube True if a cube texture needs to be created
  63455. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63456. * @param generateDepthBuffer True to generate a depth buffer
  63457. * @param generateStencilBuffer True to generate a stencil buffer
  63458. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63459. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63460. */
  63461. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63462. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63463. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63464. if (isCube === void 0) { isCube = false; }
  63465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63466. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63467. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63468. if (isMulti === void 0) { isMulti = false; }
  63469. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63470. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63471. _this.isCube = isCube;
  63472. /**
  63473. * Use this list to define the list of mesh you want to render.
  63474. */
  63475. _this.renderList = new Array();
  63476. _this.renderParticles = true;
  63477. _this.renderSprites = false;
  63478. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63479. _this.ignoreCameraViewport = false;
  63480. // Events
  63481. /**
  63482. * An event triggered when the texture is unbind.
  63483. */
  63484. _this.onBeforeBindObservable = new BABYLON.Observable();
  63485. /**
  63486. * An event triggered when the texture is unbind.
  63487. */
  63488. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63489. /**
  63490. * An event triggered before rendering the texture
  63491. */
  63492. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63493. /**
  63494. * An event triggered after rendering the texture
  63495. */
  63496. _this.onAfterRenderObservable = new BABYLON.Observable();
  63497. /**
  63498. * An event triggered after the texture clear
  63499. */
  63500. _this.onClearObservable = new BABYLON.Observable();
  63501. _this._currentRefreshId = -1;
  63502. _this._refreshRate = 1;
  63503. _this._samples = 1;
  63504. /**
  63505. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63506. * It must define where the camera used to render the texture is set
  63507. */
  63508. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63509. scene = _this.getScene();
  63510. if (!scene) {
  63511. return _this;
  63512. }
  63513. _this._engine = scene.getEngine();
  63514. _this.name = name;
  63515. _this.isRenderTarget = true;
  63516. _this._initialSizeParameter = size;
  63517. _this._processSizeParameter(size);
  63518. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63519. });
  63520. _this._generateMipMaps = generateMipMaps ? true : false;
  63521. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63522. // Rendering groups
  63523. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63524. if (isMulti) {
  63525. return _this;
  63526. }
  63527. _this._renderTargetOptions = {
  63528. generateMipMaps: generateMipMaps,
  63529. type: type,
  63530. format: format,
  63531. samplingMode: samplingMode,
  63532. generateDepthBuffer: generateDepthBuffer,
  63533. generateStencilBuffer: generateStencilBuffer
  63534. };
  63535. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63536. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63537. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63538. }
  63539. if (isCube) {
  63540. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63541. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63542. _this._textureMatrix = BABYLON.Matrix.Identity();
  63543. }
  63544. else {
  63545. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63546. }
  63547. return _this;
  63548. }
  63549. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63550. get: function () {
  63551. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63552. },
  63553. enumerable: true,
  63554. configurable: true
  63555. });
  63556. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63557. get: function () {
  63558. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63559. },
  63560. enumerable: true,
  63561. configurable: true
  63562. });
  63563. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63564. get: function () {
  63565. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63566. },
  63567. enumerable: true,
  63568. configurable: true
  63569. });
  63570. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63571. set: function (callback) {
  63572. if (this._onAfterUnbindObserver) {
  63573. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63574. }
  63575. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63576. },
  63577. enumerable: true,
  63578. configurable: true
  63579. });
  63580. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63581. set: function (callback) {
  63582. if (this._onBeforeRenderObserver) {
  63583. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63584. }
  63585. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63586. },
  63587. enumerable: true,
  63588. configurable: true
  63589. });
  63590. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63591. set: function (callback) {
  63592. if (this._onAfterRenderObserver) {
  63593. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63594. }
  63595. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63596. },
  63597. enumerable: true,
  63598. configurable: true
  63599. });
  63600. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63601. set: function (callback) {
  63602. if (this._onClearObserver) {
  63603. this.onClearObservable.remove(this._onClearObserver);
  63604. }
  63605. this._onClearObserver = this.onClearObservable.add(callback);
  63606. },
  63607. enumerable: true,
  63608. configurable: true
  63609. });
  63610. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63611. get: function () {
  63612. return this._renderTargetOptions;
  63613. },
  63614. enumerable: true,
  63615. configurable: true
  63616. });
  63617. RenderTargetTexture.prototype._onRatioRescale = function () {
  63618. if (this._sizeRatio) {
  63619. this.resize(this._initialSizeParameter);
  63620. }
  63621. };
  63622. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63623. get: function () {
  63624. return this._boundingBoxSize;
  63625. },
  63626. /**
  63627. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63628. * When defined, the cubemap will switch to local mode
  63629. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63630. * @example https://www.babylonjs-playground.com/#RNASML
  63631. */
  63632. set: function (value) {
  63633. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63634. return;
  63635. }
  63636. this._boundingBoxSize = value;
  63637. var scene = this.getScene();
  63638. if (scene) {
  63639. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63640. }
  63641. },
  63642. enumerable: true,
  63643. configurable: true
  63644. });
  63645. /**
  63646. * Creates a depth stencil texture.
  63647. * This is only available in WebGL 2 or with the depth texture extension available.
  63648. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63649. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63650. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63651. */
  63652. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63653. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63654. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63655. if (generateStencil === void 0) { generateStencil = false; }
  63656. if (!this.getScene()) {
  63657. return;
  63658. }
  63659. var engine = this.getScene().getEngine();
  63660. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63661. bilinearFiltering: bilinearFiltering,
  63662. comparisonFunction: comparisonFunction,
  63663. generateStencil: generateStencil,
  63664. isCube: this.isCube
  63665. });
  63666. engine.setFrameBufferDepthStencilTexture(this);
  63667. };
  63668. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63669. if (size.ratio) {
  63670. this._sizeRatio = size.ratio;
  63671. this._size = {
  63672. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63673. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63674. };
  63675. }
  63676. else {
  63677. this._size = size;
  63678. }
  63679. };
  63680. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63681. get: function () {
  63682. return this._samples;
  63683. },
  63684. set: function (value) {
  63685. if (this._samples === value) {
  63686. return;
  63687. }
  63688. var scene = this.getScene();
  63689. if (!scene) {
  63690. return;
  63691. }
  63692. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63693. },
  63694. enumerable: true,
  63695. configurable: true
  63696. });
  63697. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63698. this._currentRefreshId = -1;
  63699. };
  63700. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63701. get: function () {
  63702. return this._refreshRate;
  63703. },
  63704. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63705. set: function (value) {
  63706. this._refreshRate = value;
  63707. this.resetRefreshCounter();
  63708. },
  63709. enumerable: true,
  63710. configurable: true
  63711. });
  63712. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63713. if (!this._postProcessManager) {
  63714. var scene = this.getScene();
  63715. if (!scene) {
  63716. return;
  63717. }
  63718. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63719. this._postProcesses = new Array();
  63720. }
  63721. this._postProcesses.push(postProcess);
  63722. this._postProcesses[0].autoClear = false;
  63723. };
  63724. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63725. if (!this._postProcesses) {
  63726. return;
  63727. }
  63728. if (dispose) {
  63729. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63730. var postProcess = _a[_i];
  63731. postProcess.dispose();
  63732. }
  63733. }
  63734. this._postProcesses = [];
  63735. };
  63736. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63737. if (!this._postProcesses) {
  63738. return;
  63739. }
  63740. var index = this._postProcesses.indexOf(postProcess);
  63741. if (index === -1) {
  63742. return;
  63743. }
  63744. this._postProcesses.splice(index, 1);
  63745. if (this._postProcesses.length > 0) {
  63746. this._postProcesses[0].autoClear = false;
  63747. }
  63748. };
  63749. RenderTargetTexture.prototype._shouldRender = function () {
  63750. if (this._currentRefreshId === -1) { // At least render once
  63751. this._currentRefreshId = 1;
  63752. return true;
  63753. }
  63754. if (this.refreshRate === this._currentRefreshId) {
  63755. this._currentRefreshId = 1;
  63756. return true;
  63757. }
  63758. this._currentRefreshId++;
  63759. return false;
  63760. };
  63761. RenderTargetTexture.prototype.getRenderSize = function () {
  63762. if (this._size.width) {
  63763. return this._size.width;
  63764. }
  63765. return this._size;
  63766. };
  63767. RenderTargetTexture.prototype.getRenderWidth = function () {
  63768. if (this._size.width) {
  63769. return this._size.width;
  63770. }
  63771. return this._size;
  63772. };
  63773. RenderTargetTexture.prototype.getRenderHeight = function () {
  63774. if (this._size.width) {
  63775. return this._size.height;
  63776. }
  63777. return this._size;
  63778. };
  63779. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63780. get: function () {
  63781. return true;
  63782. },
  63783. enumerable: true,
  63784. configurable: true
  63785. });
  63786. RenderTargetTexture.prototype.scale = function (ratio) {
  63787. var newSize = this.getRenderSize() * ratio;
  63788. this.resize(newSize);
  63789. };
  63790. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63791. if (this.isCube) {
  63792. return this._textureMatrix;
  63793. }
  63794. return _super.prototype.getReflectionTextureMatrix.call(this);
  63795. };
  63796. RenderTargetTexture.prototype.resize = function (size) {
  63797. this.releaseInternalTexture();
  63798. var scene = this.getScene();
  63799. if (!scene) {
  63800. return;
  63801. }
  63802. this._processSizeParameter(size);
  63803. if (this.isCube) {
  63804. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63805. }
  63806. else {
  63807. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63808. }
  63809. };
  63810. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63811. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63812. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63813. var scene = this.getScene();
  63814. if (!scene) {
  63815. return;
  63816. }
  63817. var engine = scene.getEngine();
  63818. if (this.useCameraPostProcesses !== undefined) {
  63819. useCameraPostProcess = this.useCameraPostProcesses;
  63820. }
  63821. if (this._waitingRenderList) {
  63822. this.renderList = [];
  63823. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63824. var id = this._waitingRenderList[index];
  63825. var mesh_1 = scene.getMeshByID(id);
  63826. if (mesh_1) {
  63827. this.renderList.push(mesh_1);
  63828. }
  63829. }
  63830. delete this._waitingRenderList;
  63831. }
  63832. // Is predicate defined?
  63833. if (this.renderListPredicate) {
  63834. if (this.renderList) {
  63835. this.renderList.splice(0); // Clear previous renderList
  63836. }
  63837. else {
  63838. this.renderList = [];
  63839. }
  63840. var scene = this.getScene();
  63841. if (!scene) {
  63842. return;
  63843. }
  63844. var sceneMeshes = scene.meshes;
  63845. for (var index = 0; index < sceneMeshes.length; index++) {
  63846. var mesh = sceneMeshes[index];
  63847. if (this.renderListPredicate(mesh)) {
  63848. this.renderList.push(mesh);
  63849. }
  63850. }
  63851. }
  63852. this.onBeforeBindObservable.notifyObservers(this);
  63853. // Set custom projection.
  63854. // Needs to be before binding to prevent changing the aspect ratio.
  63855. var camera;
  63856. if (this.activeCamera) {
  63857. camera = this.activeCamera;
  63858. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63859. if (this.activeCamera !== scene.activeCamera) {
  63860. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63861. }
  63862. }
  63863. else {
  63864. camera = scene.activeCamera;
  63865. if (camera) {
  63866. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63867. }
  63868. }
  63869. // Prepare renderingManager
  63870. this._renderingManager.reset();
  63871. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63872. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63873. var sceneRenderId = scene.getRenderId();
  63874. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63875. var mesh = currentRenderList[meshIndex];
  63876. if (mesh) {
  63877. if (!mesh.isReady(this.refreshRate === 0)) {
  63878. this.resetRefreshCounter();
  63879. continue;
  63880. }
  63881. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63882. var isMasked = void 0;
  63883. if (!this.renderList && camera) {
  63884. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63885. }
  63886. else {
  63887. isMasked = false;
  63888. }
  63889. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63890. mesh._activate(sceneRenderId);
  63891. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63892. var subMesh = mesh.subMeshes[subIndex];
  63893. scene._activeIndices.addCount(subMesh.indexCount, false);
  63894. this._renderingManager.dispatch(subMesh, mesh);
  63895. }
  63896. }
  63897. }
  63898. }
  63899. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63900. var particleSystem = scene.particleSystems[particleIndex];
  63901. var emitter = particleSystem.emitter;
  63902. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63903. continue;
  63904. }
  63905. if (currentRenderList.indexOf(emitter) >= 0) {
  63906. this._renderingManager.dispatchParticles(particleSystem);
  63907. }
  63908. }
  63909. if (this.isCube) {
  63910. for (var face = 0; face < 6; face++) {
  63911. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63912. scene.incrementRenderId();
  63913. scene.resetCachedMaterial();
  63914. }
  63915. }
  63916. else {
  63917. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63918. }
  63919. this.onAfterUnbindObservable.notifyObservers(this);
  63920. if (scene.activeCamera) {
  63921. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63922. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63923. }
  63924. engine.setViewport(scene.activeCamera.viewport);
  63925. }
  63926. scene.resetCachedMaterial();
  63927. };
  63928. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63929. var minimum = 128;
  63930. var x = renderDimension * scale;
  63931. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63932. // Ensure we don't exceed the render dimension (while staying POT)
  63933. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63934. };
  63935. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63936. var _this = this;
  63937. if (!this._texture) {
  63938. return;
  63939. }
  63940. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63941. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63942. });
  63943. };
  63944. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63945. var scene = this.getScene();
  63946. if (!scene) {
  63947. return;
  63948. }
  63949. var engine = scene.getEngine();
  63950. if (!this._texture) {
  63951. return;
  63952. }
  63953. // Bind
  63954. if (this._postProcessManager) {
  63955. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63956. }
  63957. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63958. if (this._texture) {
  63959. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63960. }
  63961. }
  63962. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63963. // Clear
  63964. if (this.onClearObservable.hasObservers()) {
  63965. this.onClearObservable.notifyObservers(engine);
  63966. }
  63967. else {
  63968. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63969. }
  63970. if (!this._doNotChangeAspectRatio) {
  63971. scene.updateTransformMatrix(true);
  63972. }
  63973. // Render
  63974. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63975. if (this._postProcessManager) {
  63976. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63977. }
  63978. else if (useCameraPostProcess) {
  63979. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63980. }
  63981. if (!this._doNotChangeAspectRatio) {
  63982. scene.updateTransformMatrix(true);
  63983. }
  63984. // Dump ?
  63985. if (dumpForDebug) {
  63986. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63987. }
  63988. // Unbind
  63989. if (!this.isCube || faceIndex === 5) {
  63990. if (this.isCube) {
  63991. if (faceIndex === 5) {
  63992. engine.generateMipMapsForCubemap(this._texture);
  63993. }
  63994. }
  63995. this.unbindFrameBuffer(engine, faceIndex);
  63996. }
  63997. else {
  63998. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63999. }
  64000. };
  64001. /**
  64002. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64003. * This allowed control for front to back rendering or reversly depending of the special needs.
  64004. *
  64005. * @param renderingGroupId The rendering group id corresponding to its index
  64006. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64007. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64008. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64009. */
  64010. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64011. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64012. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64013. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64014. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64015. };
  64016. /**
  64017. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64018. *
  64019. * @param renderingGroupId The rendering group id corresponding to its index
  64020. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64021. */
  64022. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64023. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64024. };
  64025. RenderTargetTexture.prototype.clone = function () {
  64026. var textureSize = this.getSize();
  64027. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  64028. // Base texture
  64029. newTexture.hasAlpha = this.hasAlpha;
  64030. newTexture.level = this.level;
  64031. // RenderTarget Texture
  64032. newTexture.coordinatesMode = this.coordinatesMode;
  64033. if (this.renderList) {
  64034. newTexture.renderList = this.renderList.slice(0);
  64035. }
  64036. return newTexture;
  64037. };
  64038. RenderTargetTexture.prototype.serialize = function () {
  64039. if (!this.name) {
  64040. return null;
  64041. }
  64042. var serializationObject = _super.prototype.serialize.call(this);
  64043. serializationObject.renderTargetSize = this.getRenderSize();
  64044. serializationObject.renderList = [];
  64045. if (this.renderList) {
  64046. for (var index = 0; index < this.renderList.length; index++) {
  64047. serializationObject.renderList.push(this.renderList[index].id);
  64048. }
  64049. }
  64050. return serializationObject;
  64051. };
  64052. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64053. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64054. var objBuffer = this.getInternalTexture();
  64055. var scene = this.getScene();
  64056. if (objBuffer && scene) {
  64057. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64058. }
  64059. };
  64060. RenderTargetTexture.prototype.dispose = function () {
  64061. if (this._postProcessManager) {
  64062. this._postProcessManager.dispose();
  64063. this._postProcessManager = null;
  64064. }
  64065. this.clearPostProcesses(true);
  64066. if (this._resizeObserver) {
  64067. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64068. this._resizeObserver = null;
  64069. }
  64070. this.renderList = null;
  64071. // Remove from custom render targets
  64072. var scene = this.getScene();
  64073. if (!scene) {
  64074. return;
  64075. }
  64076. var index = scene.customRenderTargets.indexOf(this);
  64077. if (index >= 0) {
  64078. scene.customRenderTargets.splice(index, 1);
  64079. }
  64080. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64081. var camera = _a[_i];
  64082. index = camera.customRenderTargets.indexOf(this);
  64083. if (index >= 0) {
  64084. camera.customRenderTargets.splice(index, 1);
  64085. }
  64086. }
  64087. _super.prototype.dispose.call(this);
  64088. };
  64089. RenderTargetTexture.prototype._rebuild = function () {
  64090. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64091. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64092. }
  64093. if (this._postProcessManager) {
  64094. this._postProcessManager._rebuild();
  64095. }
  64096. };
  64097. /**
  64098. * Clear the info related to rendering groups preventing retention point in material dispose.
  64099. */
  64100. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64101. if (this._renderingManager) {
  64102. this._renderingManager.freeRenderingGroups();
  64103. }
  64104. };
  64105. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64106. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64107. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64108. return RenderTargetTexture;
  64109. }(BABYLON.Texture));
  64110. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64111. })(BABYLON || (BABYLON = {}));
  64112. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64113. var BABYLON;
  64114. (function (BABYLON) {
  64115. ;
  64116. var MultiRenderTarget = /** @class */ (function (_super) {
  64117. __extends(MultiRenderTarget, _super);
  64118. function MultiRenderTarget(name, size, count, scene, options) {
  64119. var _this = this;
  64120. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64121. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64122. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64123. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64124. _this._engine = scene.getEngine();
  64125. if (!_this.isSupported) {
  64126. _this.dispose();
  64127. return;
  64128. }
  64129. var types = [];
  64130. var samplingModes = [];
  64131. for (var i = 0; i < count; i++) {
  64132. if (options && options.types && options.types[i] !== undefined) {
  64133. types.push(options.types[i]);
  64134. }
  64135. else {
  64136. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64137. }
  64138. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64139. samplingModes.push(options.samplingModes[i]);
  64140. }
  64141. else {
  64142. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64143. }
  64144. }
  64145. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64146. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64147. _this._size = size;
  64148. _this._multiRenderTargetOptions = {
  64149. samplingModes: samplingModes,
  64150. generateMipMaps: generateMipMaps,
  64151. generateDepthBuffer: generateDepthBuffer,
  64152. generateStencilBuffer: generateStencilBuffer,
  64153. generateDepthTexture: generateDepthTexture,
  64154. types: types,
  64155. textureCount: count
  64156. };
  64157. _this._createInternalTextures();
  64158. _this._createTextures();
  64159. return _this;
  64160. }
  64161. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64162. get: function () {
  64163. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64164. },
  64165. enumerable: true,
  64166. configurable: true
  64167. });
  64168. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64169. get: function () {
  64170. return this._textures;
  64171. },
  64172. enumerable: true,
  64173. configurable: true
  64174. });
  64175. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64176. get: function () {
  64177. return this._textures[this._textures.length - 1];
  64178. },
  64179. enumerable: true,
  64180. configurable: true
  64181. });
  64182. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64183. set: function (wrap) {
  64184. if (this._textures) {
  64185. for (var i = 0; i < this._textures.length; i++) {
  64186. this._textures[i].wrapU = wrap;
  64187. }
  64188. }
  64189. },
  64190. enumerable: true,
  64191. configurable: true
  64192. });
  64193. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64194. set: function (wrap) {
  64195. if (this._textures) {
  64196. for (var i = 0; i < this._textures.length; i++) {
  64197. this._textures[i].wrapV = wrap;
  64198. }
  64199. }
  64200. },
  64201. enumerable: true,
  64202. configurable: true
  64203. });
  64204. MultiRenderTarget.prototype._rebuild = function () {
  64205. this.releaseInternalTextures();
  64206. this._createInternalTextures();
  64207. for (var i = 0; i < this._internalTextures.length; i++) {
  64208. var texture = this._textures[i];
  64209. texture._texture = this._internalTextures[i];
  64210. }
  64211. // Keeps references to frame buffer and stencil/depth buffer
  64212. this._texture = this._internalTextures[0];
  64213. };
  64214. MultiRenderTarget.prototype._createInternalTextures = function () {
  64215. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64216. };
  64217. MultiRenderTarget.prototype._createTextures = function () {
  64218. this._textures = [];
  64219. for (var i = 0; i < this._internalTextures.length; i++) {
  64220. var texture = new BABYLON.Texture(null, this.getScene());
  64221. texture._texture = this._internalTextures[i];
  64222. this._textures.push(texture);
  64223. }
  64224. // Keeps references to frame buffer and stencil/depth buffer
  64225. this._texture = this._internalTextures[0];
  64226. };
  64227. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64228. get: function () {
  64229. return this._samples;
  64230. },
  64231. set: function (value) {
  64232. if (this._samples === value) {
  64233. return;
  64234. }
  64235. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64236. },
  64237. enumerable: true,
  64238. configurable: true
  64239. });
  64240. MultiRenderTarget.prototype.resize = function (size) {
  64241. this.releaseInternalTextures();
  64242. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64243. this._createInternalTextures();
  64244. };
  64245. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64246. var _this = this;
  64247. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64248. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64249. });
  64250. };
  64251. MultiRenderTarget.prototype.dispose = function () {
  64252. this.releaseInternalTextures();
  64253. _super.prototype.dispose.call(this);
  64254. };
  64255. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64256. if (!this._internalTextures) {
  64257. return;
  64258. }
  64259. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64260. if (this._internalTextures[i] !== undefined) {
  64261. this._internalTextures[i].dispose();
  64262. this._internalTextures.splice(i, 1);
  64263. }
  64264. }
  64265. };
  64266. return MultiRenderTarget;
  64267. }(BABYLON.RenderTargetTexture));
  64268. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64269. })(BABYLON || (BABYLON = {}));
  64270. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64271. var BABYLON;
  64272. (function (BABYLON) {
  64273. var MirrorTexture = /** @class */ (function (_super) {
  64274. __extends(MirrorTexture, _super);
  64275. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64276. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64278. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64279. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64280. _this.scene = scene;
  64281. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64282. _this._transformMatrix = BABYLON.Matrix.Zero();
  64283. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64284. _this._adaptiveBlurKernel = 0;
  64285. _this._blurKernelX = 0;
  64286. _this._blurKernelY = 0;
  64287. _this._blurRatio = 1.0;
  64288. _this.ignoreCameraViewport = true;
  64289. _this._updateGammaSpace();
  64290. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64291. _this._updateGammaSpace;
  64292. });
  64293. _this.onBeforeRenderObservable.add(function () {
  64294. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64295. _this._savedViewMatrix = scene.getViewMatrix();
  64296. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64297. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64298. scene.clipPlane = _this.mirrorPlane;
  64299. scene.getEngine().cullBackFaces = false;
  64300. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64301. });
  64302. _this.onAfterRenderObservable.add(function () {
  64303. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64304. scene.getEngine().cullBackFaces = true;
  64305. scene._mirroredCameraPosition = null;
  64306. delete scene.clipPlane;
  64307. });
  64308. return _this;
  64309. }
  64310. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64311. get: function () {
  64312. return this._blurRatio;
  64313. },
  64314. set: function (value) {
  64315. if (this._blurRatio === value) {
  64316. return;
  64317. }
  64318. this._blurRatio = value;
  64319. this._preparePostProcesses();
  64320. },
  64321. enumerable: true,
  64322. configurable: true
  64323. });
  64324. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64325. set: function (value) {
  64326. this._adaptiveBlurKernel = value;
  64327. this._autoComputeBlurKernel();
  64328. },
  64329. enumerable: true,
  64330. configurable: true
  64331. });
  64332. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64333. set: function (value) {
  64334. this.blurKernelX = value;
  64335. this.blurKernelY = value;
  64336. },
  64337. enumerable: true,
  64338. configurable: true
  64339. });
  64340. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64341. get: function () {
  64342. return this._blurKernelX;
  64343. },
  64344. set: function (value) {
  64345. if (this._blurKernelX === value) {
  64346. return;
  64347. }
  64348. this._blurKernelX = value;
  64349. this._preparePostProcesses();
  64350. },
  64351. enumerable: true,
  64352. configurable: true
  64353. });
  64354. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64355. get: function () {
  64356. return this._blurKernelY;
  64357. },
  64358. set: function (value) {
  64359. if (this._blurKernelY === value) {
  64360. return;
  64361. }
  64362. this._blurKernelY = value;
  64363. this._preparePostProcesses();
  64364. },
  64365. enumerable: true,
  64366. configurable: true
  64367. });
  64368. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64369. var engine = this.getScene().getEngine();
  64370. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64371. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64372. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64373. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64374. };
  64375. MirrorTexture.prototype._onRatioRescale = function () {
  64376. if (this._sizeRatio) {
  64377. this.resize(this._initialSizeParameter);
  64378. if (!this._adaptiveBlurKernel) {
  64379. this._preparePostProcesses();
  64380. }
  64381. }
  64382. if (this._adaptiveBlurKernel) {
  64383. this._autoComputeBlurKernel();
  64384. }
  64385. };
  64386. MirrorTexture.prototype._updateGammaSpace = function () {
  64387. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64388. };
  64389. MirrorTexture.prototype._preparePostProcesses = function () {
  64390. this.clearPostProcesses(true);
  64391. if (this._blurKernelX && this._blurKernelY) {
  64392. var engine = this.getScene().getEngine();
  64393. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64394. 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);
  64395. this._blurX.autoClear = false;
  64396. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64397. this._blurX.inputTexture = this._texture;
  64398. }
  64399. else {
  64400. this._blurX.alwaysForcePOT = true;
  64401. }
  64402. 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);
  64403. this._blurY.autoClear = false;
  64404. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64405. this.addPostProcess(this._blurX);
  64406. this.addPostProcess(this._blurY);
  64407. }
  64408. else {
  64409. if (this._blurY) {
  64410. this.removePostProcess(this._blurY);
  64411. this._blurY.dispose();
  64412. this._blurY = null;
  64413. }
  64414. if (this._blurX) {
  64415. this.removePostProcess(this._blurX);
  64416. this._blurX.dispose();
  64417. this._blurX = null;
  64418. }
  64419. }
  64420. };
  64421. MirrorTexture.prototype.clone = function () {
  64422. var scene = this.getScene();
  64423. if (!scene) {
  64424. return this;
  64425. }
  64426. var textureSize = this.getSize();
  64427. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64428. // Base texture
  64429. newTexture.hasAlpha = this.hasAlpha;
  64430. newTexture.level = this.level;
  64431. // Mirror Texture
  64432. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64433. if (this.renderList) {
  64434. newTexture.renderList = this.renderList.slice(0);
  64435. }
  64436. return newTexture;
  64437. };
  64438. MirrorTexture.prototype.serialize = function () {
  64439. if (!this.name) {
  64440. return null;
  64441. }
  64442. var serializationObject = _super.prototype.serialize.call(this);
  64443. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64444. return serializationObject;
  64445. };
  64446. MirrorTexture.prototype.dispose = function () {
  64447. _super.prototype.dispose.call(this);
  64448. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64449. };
  64450. return MirrorTexture;
  64451. }(BABYLON.RenderTargetTexture));
  64452. BABYLON.MirrorTexture = MirrorTexture;
  64453. })(BABYLON || (BABYLON = {}));
  64454. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64455. var BABYLON;
  64456. (function (BABYLON) {
  64457. /**
  64458. * Creates a refraction texture used by refraction channel of the standard material.
  64459. * @param name the texture name
  64460. * @param size size of the underlying texture
  64461. * @param scene root scene
  64462. */
  64463. var RefractionTexture = /** @class */ (function (_super) {
  64464. __extends(RefractionTexture, _super);
  64465. function RefractionTexture(name, size, scene, generateMipMaps) {
  64466. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64467. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64468. _this.depth = 2.0;
  64469. _this.onBeforeRenderObservable.add(function () {
  64470. scene.clipPlane = _this.refractionPlane;
  64471. });
  64472. _this.onAfterRenderObservable.add(function () {
  64473. delete scene.clipPlane;
  64474. });
  64475. return _this;
  64476. }
  64477. RefractionTexture.prototype.clone = function () {
  64478. var scene = this.getScene();
  64479. if (!scene) {
  64480. return this;
  64481. }
  64482. var textureSize = this.getSize();
  64483. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64484. // Base texture
  64485. newTexture.hasAlpha = this.hasAlpha;
  64486. newTexture.level = this.level;
  64487. // Refraction Texture
  64488. newTexture.refractionPlane = this.refractionPlane.clone();
  64489. if (this.renderList) {
  64490. newTexture.renderList = this.renderList.slice(0);
  64491. }
  64492. newTexture.depth = this.depth;
  64493. return newTexture;
  64494. };
  64495. RefractionTexture.prototype.serialize = function () {
  64496. if (!this.name) {
  64497. return null;
  64498. }
  64499. var serializationObject = _super.prototype.serialize.call(this);
  64500. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64501. serializationObject.depth = this.depth;
  64502. return serializationObject;
  64503. };
  64504. return RefractionTexture;
  64505. }(BABYLON.RenderTargetTexture));
  64506. BABYLON.RefractionTexture = RefractionTexture;
  64507. })(BABYLON || (BABYLON = {}));
  64508. //# sourceMappingURL=babylon.refractionTexture.js.map
  64509. var BABYLON;
  64510. (function (BABYLON) {
  64511. /**
  64512. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64513. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64514. */
  64515. var DynamicTexture = /** @class */ (function (_super) {
  64516. __extends(DynamicTexture, _super);
  64517. /**
  64518. * Creates a {BABYLON.DynamicTexture}
  64519. * @param name defines the name of the texture
  64520. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  64521. * @param scene defines the scene where you want the texture
  64522. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64523. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64524. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64525. */
  64526. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64527. if (scene === void 0) { scene = null; }
  64528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64529. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64530. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64531. _this.name = name;
  64532. _this._engine = _this.getScene().getEngine();
  64533. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64534. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64535. _this._generateMipMaps = generateMipMaps;
  64536. if (options.getContext) {
  64537. _this._canvas = options;
  64538. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64539. }
  64540. else {
  64541. _this._canvas = document.createElement("canvas");
  64542. if (options.width || options.width === 0) {
  64543. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64544. }
  64545. else {
  64546. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64547. }
  64548. }
  64549. var textureSize = _this.getSize();
  64550. _this._canvas.width = textureSize.width;
  64551. _this._canvas.height = textureSize.height;
  64552. _this._context = _this._canvas.getContext("2d");
  64553. return _this;
  64554. }
  64555. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64556. /**
  64557. * Gets the current state of canRescale
  64558. */
  64559. get: function () {
  64560. return true;
  64561. },
  64562. enumerable: true,
  64563. configurable: true
  64564. });
  64565. DynamicTexture.prototype._recreate = function (textureSize) {
  64566. this._canvas.width = textureSize.width;
  64567. this._canvas.height = textureSize.height;
  64568. this.releaseInternalTexture();
  64569. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64570. };
  64571. /**
  64572. * Scales the texture
  64573. * @param ratio the scale factor to apply to both width and height
  64574. */
  64575. DynamicTexture.prototype.scale = function (ratio) {
  64576. var textureSize = this.getSize();
  64577. textureSize.width *= ratio;
  64578. textureSize.height *= ratio;
  64579. this._recreate(textureSize);
  64580. };
  64581. /**
  64582. * Resizes the texture
  64583. * @param width the new width
  64584. * @param height the new height
  64585. */
  64586. DynamicTexture.prototype.scaleTo = function (width, height) {
  64587. var textureSize = this.getSize();
  64588. textureSize.width = width;
  64589. textureSize.height = height;
  64590. this._recreate(textureSize);
  64591. };
  64592. /**
  64593. * Gets the context of the canvas used by the texture
  64594. * @returns the canvas context of the dynamic texture
  64595. */
  64596. DynamicTexture.prototype.getContext = function () {
  64597. return this._context;
  64598. };
  64599. /**
  64600. * Clears the texture
  64601. */
  64602. DynamicTexture.prototype.clear = function () {
  64603. var size = this.getSize();
  64604. this._context.fillRect(0, 0, size.width, size.height);
  64605. };
  64606. /**
  64607. * Updates the texture
  64608. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64609. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64610. */
  64611. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64612. if (premulAlpha === void 0) { premulAlpha = false; }
  64613. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64614. };
  64615. /**
  64616. * Draws text onto the texture
  64617. * @param text defines the text to be drawn
  64618. * @param x defines the placement of the text from the left
  64619. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64620. * @param font defines the font to be used with font-style, font-size, font-name
  64621. * @param color defines the color used for the text
  64622. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64623. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64624. * @param update defines whether texture is immediately update (default is true)
  64625. */
  64626. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64627. if (update === void 0) { update = true; }
  64628. var size = this.getSize();
  64629. if (clearColor) {
  64630. this._context.fillStyle = clearColor;
  64631. this._context.fillRect(0, 0, size.width, size.height);
  64632. }
  64633. this._context.font = font;
  64634. if (x === null || x === undefined) {
  64635. var textSize = this._context.measureText(text);
  64636. x = (size.width - textSize.width) / 2;
  64637. }
  64638. if (y === null || y === undefined) {
  64639. var fontSize = parseInt((font.replace(/\D/g, '')));
  64640. y = (size.height / 2) + (fontSize / 3.65);
  64641. }
  64642. this._context.fillStyle = color;
  64643. this._context.fillText(text, x, y);
  64644. if (update) {
  64645. this.update(invertY);
  64646. }
  64647. };
  64648. /**
  64649. * Clones the texture
  64650. * @returns the clone of the texture.
  64651. */
  64652. DynamicTexture.prototype.clone = function () {
  64653. var scene = this.getScene();
  64654. if (!scene) {
  64655. return this;
  64656. }
  64657. var textureSize = this.getSize();
  64658. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64659. // Base texture
  64660. newTexture.hasAlpha = this.hasAlpha;
  64661. newTexture.level = this.level;
  64662. // Dynamic Texture
  64663. newTexture.wrapU = this.wrapU;
  64664. newTexture.wrapV = this.wrapV;
  64665. return newTexture;
  64666. };
  64667. /** @hidden */
  64668. DynamicTexture.prototype._rebuild = function () {
  64669. this.update();
  64670. };
  64671. return DynamicTexture;
  64672. }(BABYLON.Texture));
  64673. BABYLON.DynamicTexture = DynamicTexture;
  64674. })(BABYLON || (BABYLON = {}));
  64675. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64676. var BABYLON;
  64677. (function (BABYLON) {
  64678. var VideoTexture = /** @class */ (function (_super) {
  64679. __extends(VideoTexture, _super);
  64680. /**
  64681. * Creates a video texture.
  64682. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64683. * @param {string | null} name optional name, will detect from video source, if not defined
  64684. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64685. * @param {BABYLON.Scene} scene is obviously the current scene.
  64686. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64687. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64688. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64689. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64690. */
  64691. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64692. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64693. if (invertY === void 0) { invertY = false; }
  64694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64695. if (settings === void 0) { settings = {
  64696. autoPlay: true,
  64697. loop: true,
  64698. autoUpdateTexture: true,
  64699. }; }
  64700. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64701. _this._onUserActionRequestedObservable = null;
  64702. _this._stillImageCaptured = false;
  64703. _this._createInternalTexture = function () {
  64704. if (_this._texture != null) {
  64705. return;
  64706. }
  64707. if (!_this._engine.needPOTTextures ||
  64708. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64709. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64710. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64711. }
  64712. else {
  64713. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64714. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64715. _this._generateMipMaps = false;
  64716. }
  64717. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64718. if (!_this.video.autoplay) {
  64719. var oldHandler_1 = _this.video.onplaying;
  64720. var error_1 = false;
  64721. _this.video.onplaying = function () {
  64722. _this.video.onplaying = oldHandler_1;
  64723. _this._texture.isReady = true;
  64724. _this._updateInternalTexture();
  64725. if (!error_1) {
  64726. _this.video.pause();
  64727. }
  64728. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64729. _this.onLoadObservable.notifyObservers(_this);
  64730. }
  64731. };
  64732. var playing = _this.video.play();
  64733. if (playing) {
  64734. playing.then(function () {
  64735. // Everything is good.
  64736. })
  64737. .catch(function () {
  64738. error_1 = true;
  64739. // On Chrome for instance, new policies might prevent playing without user interaction.
  64740. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64741. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64742. }
  64743. });
  64744. }
  64745. else {
  64746. _this.video.onplaying = oldHandler_1;
  64747. _this._texture.isReady = true;
  64748. _this._updateInternalTexture();
  64749. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64750. _this.onLoadObservable.notifyObservers(_this);
  64751. }
  64752. }
  64753. }
  64754. else {
  64755. _this._texture.isReady = true;
  64756. _this._updateInternalTexture();
  64757. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64758. _this.onLoadObservable.notifyObservers(_this);
  64759. }
  64760. }
  64761. };
  64762. _this.reset = function () {
  64763. if (_this._texture == null) {
  64764. return;
  64765. }
  64766. _this._texture.dispose();
  64767. _this._texture = null;
  64768. };
  64769. _this._updateInternalTexture = function (e) {
  64770. if (_this._texture == null || !_this._texture.isReady) {
  64771. return;
  64772. }
  64773. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64774. return;
  64775. }
  64776. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64777. };
  64778. _this._engine = _this.getScene().getEngine();
  64779. _this._generateMipMaps = generateMipMaps;
  64780. _this._samplingMode = samplingMode;
  64781. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64782. _this.name = name || _this._getName(src);
  64783. _this.video = _this._getVideo(src);
  64784. if (settings.poster) {
  64785. _this.video.poster = settings.poster;
  64786. }
  64787. if (settings.autoPlay !== undefined) {
  64788. _this.video.autoplay = settings.autoPlay;
  64789. }
  64790. if (settings.loop !== undefined) {
  64791. _this.video.loop = settings.loop;
  64792. }
  64793. _this.video.setAttribute("playsinline", "");
  64794. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64795. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64796. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64797. _this.video.addEventListener("emptied", _this.reset);
  64798. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64799. _this._createInternalTexture();
  64800. }
  64801. return _this;
  64802. }
  64803. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64804. get: function () {
  64805. if (!this._onUserActionRequestedObservable) {
  64806. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64807. }
  64808. return this._onUserActionRequestedObservable;
  64809. },
  64810. enumerable: true,
  64811. configurable: true
  64812. });
  64813. VideoTexture.prototype._getName = function (src) {
  64814. if (src instanceof HTMLVideoElement) {
  64815. return src.currentSrc;
  64816. }
  64817. if (typeof src === "object") {
  64818. return src.toString();
  64819. }
  64820. return src;
  64821. };
  64822. ;
  64823. VideoTexture.prototype._getVideo = function (src) {
  64824. if (src instanceof HTMLVideoElement) {
  64825. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64826. return src;
  64827. }
  64828. var video = document.createElement("video");
  64829. if (typeof src === "string") {
  64830. BABYLON.Tools.SetCorsBehavior(src, video);
  64831. video.src = src;
  64832. }
  64833. else {
  64834. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64835. src.forEach(function (url) {
  64836. var source = document.createElement("source");
  64837. source.src = url;
  64838. video.appendChild(source);
  64839. });
  64840. }
  64841. return video;
  64842. };
  64843. ;
  64844. /**
  64845. * Internal method to initiate `update`.
  64846. */
  64847. VideoTexture.prototype._rebuild = function () {
  64848. this.update();
  64849. };
  64850. /**
  64851. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64852. */
  64853. VideoTexture.prototype.update = function () {
  64854. if (!this.autoUpdateTexture) {
  64855. // Expecting user to call `updateTexture` manually
  64856. return;
  64857. }
  64858. this.updateTexture(true);
  64859. };
  64860. /**
  64861. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64862. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64863. */
  64864. VideoTexture.prototype.updateTexture = function (isVisible) {
  64865. if (!isVisible) {
  64866. return;
  64867. }
  64868. if (this.video.paused && this._stillImageCaptured) {
  64869. return;
  64870. }
  64871. this._stillImageCaptured = true;
  64872. this._updateInternalTexture();
  64873. };
  64874. /**
  64875. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64876. * @param url New url.
  64877. */
  64878. VideoTexture.prototype.updateURL = function (url) {
  64879. this.video.src = url;
  64880. };
  64881. VideoTexture.prototype.dispose = function () {
  64882. _super.prototype.dispose.call(this);
  64883. if (this._onUserActionRequestedObservable) {
  64884. this._onUserActionRequestedObservable.clear();
  64885. this._onUserActionRequestedObservable = null;
  64886. }
  64887. this.video.removeEventListener("canplay", this._createInternalTexture);
  64888. this.video.removeEventListener("paused", this._updateInternalTexture);
  64889. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64890. this.video.removeEventListener("emptied", this.reset);
  64891. this.video.pause();
  64892. };
  64893. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64894. var video = document.createElement("video");
  64895. video.setAttribute('autoplay', '');
  64896. video.setAttribute('muted', '');
  64897. video.setAttribute('playsinline', '');
  64898. var constraintsDeviceId;
  64899. if (constraints && constraints.deviceId) {
  64900. constraintsDeviceId = {
  64901. exact: constraints.deviceId,
  64902. };
  64903. }
  64904. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64905. if (navigator.mediaDevices) {
  64906. navigator.mediaDevices.getUserMedia({ video: constraints })
  64907. .then(function (stream) {
  64908. if (video.mozSrcObject !== undefined) {
  64909. // hack for Firefox < 19
  64910. video.mozSrcObject = stream;
  64911. }
  64912. else {
  64913. video.srcObject = stream;
  64914. }
  64915. var onPlaying = function () {
  64916. if (onReady) {
  64917. onReady(new VideoTexture("video", video, scene, true, true));
  64918. }
  64919. video.removeEventListener("playing", onPlaying);
  64920. };
  64921. video.addEventListener("playing", onPlaying);
  64922. video.play();
  64923. })
  64924. .catch(function (err) {
  64925. BABYLON.Tools.Error(err.name);
  64926. });
  64927. }
  64928. else {
  64929. navigator.getUserMedia =
  64930. navigator.getUserMedia ||
  64931. navigator.webkitGetUserMedia ||
  64932. navigator.mozGetUserMedia ||
  64933. navigator.msGetUserMedia;
  64934. if (navigator.getUserMedia) {
  64935. navigator.getUserMedia({
  64936. video: {
  64937. deviceId: constraintsDeviceId,
  64938. width: {
  64939. min: (constraints && constraints.minWidth) || 256,
  64940. max: (constraints && constraints.maxWidth) || 640,
  64941. },
  64942. height: {
  64943. min: (constraints && constraints.minHeight) || 256,
  64944. max: (constraints && constraints.maxHeight) || 480,
  64945. },
  64946. },
  64947. }, function (stream) {
  64948. if (video.mozSrcObject !== undefined) {
  64949. // hack for Firefox < 19
  64950. video.mozSrcObject = stream;
  64951. }
  64952. else {
  64953. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64954. }
  64955. video.play();
  64956. if (onReady) {
  64957. onReady(new VideoTexture("video", video, scene, true, true));
  64958. }
  64959. }, function (e) {
  64960. BABYLON.Tools.Error(e.name);
  64961. });
  64962. }
  64963. }
  64964. };
  64965. return VideoTexture;
  64966. }(BABYLON.Texture));
  64967. BABYLON.VideoTexture = VideoTexture;
  64968. })(BABYLON || (BABYLON = {}));
  64969. //# sourceMappingURL=babylon.videoTexture.js.map
  64970. var BABYLON;
  64971. (function (BABYLON) {
  64972. var RawTexture = /** @class */ (function (_super) {
  64973. __extends(RawTexture, _super);
  64974. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64975. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64976. if (invertY === void 0) { invertY = false; }
  64977. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64978. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64979. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64980. _this.format = format;
  64981. _this._engine = scene.getEngine();
  64982. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64983. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64984. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64985. return _this;
  64986. }
  64987. RawTexture.prototype.update = function (data) {
  64988. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64989. };
  64990. // Statics
  64991. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64992. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64993. if (invertY === void 0) { invertY = false; }
  64994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64995. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64996. };
  64997. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64998. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64999. if (invertY === void 0) { invertY = false; }
  65000. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65001. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65002. };
  65003. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65004. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65005. if (invertY === void 0) { invertY = false; }
  65006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65007. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65008. };
  65009. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65010. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65011. if (invertY === void 0) { invertY = false; }
  65012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65013. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65014. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65015. };
  65016. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65017. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65018. if (invertY === void 0) { invertY = false; }
  65019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65020. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65021. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65022. };
  65023. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65024. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65025. if (invertY === void 0) { invertY = false; }
  65026. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65027. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65028. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65029. };
  65030. return RawTexture;
  65031. }(BABYLON.Texture));
  65032. BABYLON.RawTexture = RawTexture;
  65033. })(BABYLON || (BABYLON = {}));
  65034. //# sourceMappingURL=babylon.rawTexture.js.map
  65035. var BABYLON;
  65036. (function (BABYLON) {
  65037. /**
  65038. * Class used to store 3D textures containing user data
  65039. */
  65040. var RawTexture3D = /** @class */ (function (_super) {
  65041. __extends(RawTexture3D, _super);
  65042. /**
  65043. * Create a new RawTexture3D
  65044. * @param data defines the data of the texture
  65045. * @param width defines the width of the texture
  65046. * @param height defines the height of the texture
  65047. * @param depth defines the depth of the texture
  65048. * @param format defines the texture format to use
  65049. * @param scene defines the hosting scene
  65050. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65051. * @param invertY defines if texture must be stored with Y axis inverted
  65052. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65053. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65054. */
  65055. function RawTexture3D(data, width, height, depth,
  65056. /** Gets or sets the texture format to use */
  65057. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65058. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65059. if (invertY === void 0) { invertY = false; }
  65060. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65061. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65062. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65063. _this.format = format;
  65064. _this._engine = scene.getEngine();
  65065. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65066. _this.is3D = true;
  65067. return _this;
  65068. }
  65069. /**
  65070. * Update the texture with new data
  65071. * @param data defines the data to store in the texture
  65072. */
  65073. RawTexture3D.prototype.update = function (data) {
  65074. if (!this._texture) {
  65075. return;
  65076. }
  65077. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65078. };
  65079. return RawTexture3D;
  65080. }(BABYLON.Texture));
  65081. BABYLON.RawTexture3D = RawTexture3D;
  65082. })(BABYLON || (BABYLON = {}));
  65083. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65084. var BABYLON;
  65085. (function (BABYLON) {
  65086. /**
  65087. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65088. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65089. */
  65090. var PostProcessManager = /** @class */ (function () {
  65091. /**
  65092. * Creates a new instance PostProcess
  65093. * @param scene The scene that the post process is associated with.
  65094. */
  65095. function PostProcessManager(scene) {
  65096. this._vertexBuffers = {};
  65097. this._scene = scene;
  65098. }
  65099. PostProcessManager.prototype._prepareBuffers = function () {
  65100. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65101. return;
  65102. }
  65103. // VBO
  65104. var vertices = [];
  65105. vertices.push(1, 1);
  65106. vertices.push(-1, 1);
  65107. vertices.push(-1, -1);
  65108. vertices.push(1, -1);
  65109. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65110. this._buildIndexBuffer();
  65111. };
  65112. PostProcessManager.prototype._buildIndexBuffer = function () {
  65113. // Indices
  65114. var indices = [];
  65115. indices.push(0);
  65116. indices.push(1);
  65117. indices.push(2);
  65118. indices.push(0);
  65119. indices.push(2);
  65120. indices.push(3);
  65121. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65122. };
  65123. /**
  65124. * Rebuilds the vertex buffers of the manager.
  65125. */
  65126. PostProcessManager.prototype._rebuild = function () {
  65127. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65128. if (!vb) {
  65129. return;
  65130. }
  65131. vb._rebuild();
  65132. this._buildIndexBuffer();
  65133. };
  65134. // Methods
  65135. /**
  65136. * Prepares a frame to be run through a post process.
  65137. * @param sourceTexture The input texture to the post procesess. (default: null)
  65138. * @param postProcesses An array of post processes to be run. (default: null)
  65139. * @returns True if the post processes were able to be run.
  65140. */
  65141. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65142. if (sourceTexture === void 0) { sourceTexture = null; }
  65143. if (postProcesses === void 0) { postProcesses = null; }
  65144. var camera = this._scene.activeCamera;
  65145. if (!camera) {
  65146. return false;
  65147. }
  65148. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65149. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65150. return false;
  65151. }
  65152. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65153. return true;
  65154. };
  65155. /**
  65156. * Manually render a set of post processes to a texture.
  65157. * @param postProcesses An array of post processes to be run.
  65158. * @param targetTexture The target texture to render to.
  65159. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65160. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65161. * @param lodLevel defines which lod of the texture to render to
  65162. */
  65163. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65164. if (targetTexture === void 0) { targetTexture = null; }
  65165. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65166. if (faceIndex === void 0) { faceIndex = 0; }
  65167. if (lodLevel === void 0) { lodLevel = 0; }
  65168. var engine = this._scene.getEngine();
  65169. for (var index = 0; index < postProcesses.length; index++) {
  65170. if (index < postProcesses.length - 1) {
  65171. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65172. }
  65173. else {
  65174. if (targetTexture) {
  65175. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65176. }
  65177. else {
  65178. engine.restoreDefaultFramebuffer();
  65179. }
  65180. }
  65181. var pp = postProcesses[index];
  65182. var effect = pp.apply();
  65183. if (effect) {
  65184. pp.onBeforeRenderObservable.notifyObservers(effect);
  65185. // VBOs
  65186. this._prepareBuffers();
  65187. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65188. // Draw order
  65189. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65190. pp.onAfterRenderObservable.notifyObservers(effect);
  65191. }
  65192. }
  65193. // Restore depth buffer
  65194. engine.setDepthBuffer(true);
  65195. engine.setDepthWrite(true);
  65196. };
  65197. /**
  65198. * Finalize the result of the output of the postprocesses.
  65199. * @param doNotPresent If true the result will not be displayed to the screen.
  65200. * @param targetTexture The target texture to render to.
  65201. * @param faceIndex The index of the face to bind the target texture to.
  65202. * @param postProcesses The array of post processes to render.
  65203. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65204. */
  65205. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65206. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65207. var camera = this._scene.activeCamera;
  65208. if (!camera) {
  65209. return;
  65210. }
  65211. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65212. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65213. return;
  65214. }
  65215. var engine = this._scene.getEngine();
  65216. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65217. var pp = postProcesses[index];
  65218. if (index < len - 1) {
  65219. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65220. }
  65221. else {
  65222. if (targetTexture) {
  65223. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65224. pp._outputTexture = targetTexture;
  65225. }
  65226. else {
  65227. engine.restoreDefaultFramebuffer();
  65228. pp._outputTexture = null;
  65229. }
  65230. }
  65231. if (doNotPresent) {
  65232. break;
  65233. }
  65234. var effect = pp.apply();
  65235. if (effect) {
  65236. pp.onBeforeRenderObservable.notifyObservers(effect);
  65237. // VBOs
  65238. this._prepareBuffers();
  65239. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65240. // Draw order
  65241. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65242. pp.onAfterRenderObservable.notifyObservers(effect);
  65243. }
  65244. }
  65245. // Restore states
  65246. engine.setDepthBuffer(true);
  65247. engine.setDepthWrite(true);
  65248. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65249. };
  65250. /**
  65251. * Disposes of the post process manager.
  65252. */
  65253. PostProcessManager.prototype.dispose = function () {
  65254. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65255. if (buffer) {
  65256. buffer.dispose();
  65257. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65258. }
  65259. if (this._indexBuffer) {
  65260. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65261. this._indexBuffer = null;
  65262. }
  65263. };
  65264. return PostProcessManager;
  65265. }());
  65266. BABYLON.PostProcessManager = PostProcessManager;
  65267. })(BABYLON || (BABYLON = {}));
  65268. //# sourceMappingURL=babylon.postProcessManager.js.map
  65269. var BABYLON;
  65270. (function (BABYLON) {
  65271. /**
  65272. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65273. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65274. */
  65275. var PostProcess = /** @class */ (function () {
  65276. /**
  65277. * Creates a new instance PostProcess
  65278. * @param name The name of the PostProcess.
  65279. * @param fragmentUrl The url of the fragment shader to be used.
  65280. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65281. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65282. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65283. * @param camera The camera to apply the render pass to.
  65284. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65285. * @param engine The engine which the post process will be applied. (default: current engine)
  65286. * @param reusable If the post process can be reused on the same frame. (default: false)
  65287. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65288. * @param textureType Type of textures used when performing the post process. (default: 0)
  65289. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65290. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  65291. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65292. */
  65293. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65295. if (defines === void 0) { defines = null; }
  65296. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65297. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65298. if (blockCompilation === void 0) { blockCompilation = false; }
  65299. this.name = name;
  65300. /**
  65301. * Width of the texture to apply the post process on
  65302. */
  65303. this.width = -1;
  65304. /**
  65305. * Height of the texture to apply the post process on
  65306. */
  65307. this.height = -1;
  65308. /**
  65309. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65310. */
  65311. this._outputTexture = null;
  65312. /**
  65313. * If the buffer needs to be cleared before applying the post process. (default: true)
  65314. * Should be set to false if shader will overwrite all previous pixels.
  65315. */
  65316. this.autoClear = true;
  65317. /**
  65318. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65319. */
  65320. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65321. /**
  65322. * Animations to be used for the post processing
  65323. */
  65324. this.animations = new Array();
  65325. /**
  65326. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65327. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65328. */
  65329. this.enablePixelPerfectMode = false;
  65330. /**
  65331. * Force the postprocess to be applied without taking in account viewport
  65332. */
  65333. this.forceFullscreenViewport = true;
  65334. /**
  65335. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65336. *
  65337. * | Value | Type | Description |
  65338. * | ----- | ----------------------------------- | ----------- |
  65339. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65340. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65341. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65342. *
  65343. */
  65344. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65345. /**
  65346. * Force textures to be a power of two (default: false)
  65347. */
  65348. this.alwaysForcePOT = false;
  65349. /**
  65350. * Number of sample textures (default: 1)
  65351. */
  65352. this.samples = 1;
  65353. /**
  65354. * Modify the scale of the post process to be the same as the viewport (default: false)
  65355. */
  65356. this.adaptScaleToCurrentViewport = false;
  65357. this._reusable = false;
  65358. /**
  65359. * Smart array of input and output textures for the post process.
  65360. */
  65361. this._textures = new BABYLON.SmartArray(2);
  65362. /**
  65363. * The index in _textures that corresponds to the output texture.
  65364. */
  65365. this._currentRenderTextureInd = 0;
  65366. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65367. this._texelSize = BABYLON.Vector2.Zero();
  65368. // Events
  65369. /**
  65370. * An event triggered when the postprocess is activated.
  65371. */
  65372. this.onActivateObservable = new BABYLON.Observable();
  65373. /**
  65374. * An event triggered when the postprocess changes its size.
  65375. */
  65376. this.onSizeChangedObservable = new BABYLON.Observable();
  65377. /**
  65378. * An event triggered when the postprocess applies its effect.
  65379. */
  65380. this.onApplyObservable = new BABYLON.Observable();
  65381. /**
  65382. * An event triggered before rendering the postprocess
  65383. */
  65384. this.onBeforeRenderObservable = new BABYLON.Observable();
  65385. /**
  65386. * An event triggered after rendering the postprocess
  65387. */
  65388. this.onAfterRenderObservable = new BABYLON.Observable();
  65389. if (camera != null) {
  65390. this._camera = camera;
  65391. this._scene = camera.getScene();
  65392. camera.attachPostProcess(this);
  65393. this._engine = this._scene.getEngine();
  65394. this._scene.postProcesses.push(this);
  65395. }
  65396. else if (engine) {
  65397. this._engine = engine;
  65398. this._engine.postProcesses.push(this);
  65399. }
  65400. this._options = options;
  65401. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65402. this._reusable = reusable || false;
  65403. this._textureType = textureType;
  65404. this._samplers = samplers || [];
  65405. this._samplers.push("textureSampler");
  65406. this._fragmentUrl = fragmentUrl;
  65407. this._vertexUrl = vertexUrl;
  65408. this._parameters = parameters || [];
  65409. this._parameters.push("scale");
  65410. this._indexParameters = indexParameters;
  65411. if (!blockCompilation) {
  65412. this.updateEffect(defines);
  65413. }
  65414. }
  65415. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65416. /**
  65417. * A function that is added to the onActivateObservable
  65418. */
  65419. set: function (callback) {
  65420. if (this._onActivateObserver) {
  65421. this.onActivateObservable.remove(this._onActivateObserver);
  65422. }
  65423. if (callback) {
  65424. this._onActivateObserver = this.onActivateObservable.add(callback);
  65425. }
  65426. },
  65427. enumerable: true,
  65428. configurable: true
  65429. });
  65430. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65431. /**
  65432. * A function that is added to the onSizeChangedObservable
  65433. */
  65434. set: function (callback) {
  65435. if (this._onSizeChangedObserver) {
  65436. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65437. }
  65438. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65439. },
  65440. enumerable: true,
  65441. configurable: true
  65442. });
  65443. Object.defineProperty(PostProcess.prototype, "onApply", {
  65444. /**
  65445. * A function that is added to the onApplyObservable
  65446. */
  65447. set: function (callback) {
  65448. if (this._onApplyObserver) {
  65449. this.onApplyObservable.remove(this._onApplyObserver);
  65450. }
  65451. this._onApplyObserver = this.onApplyObservable.add(callback);
  65452. },
  65453. enumerable: true,
  65454. configurable: true
  65455. });
  65456. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65457. /**
  65458. * A function that is added to the onBeforeRenderObservable
  65459. */
  65460. set: function (callback) {
  65461. if (this._onBeforeRenderObserver) {
  65462. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65463. }
  65464. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65465. },
  65466. enumerable: true,
  65467. configurable: true
  65468. });
  65469. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65470. /**
  65471. * A function that is added to the onAfterRenderObservable
  65472. */
  65473. set: function (callback) {
  65474. if (this._onAfterRenderObserver) {
  65475. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65476. }
  65477. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65478. },
  65479. enumerable: true,
  65480. configurable: true
  65481. });
  65482. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65483. /**
  65484. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  65485. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65486. */
  65487. get: function () {
  65488. return this._textures.data[this._currentRenderTextureInd];
  65489. },
  65490. set: function (value) {
  65491. this._forcedOutputTexture = value;
  65492. },
  65493. enumerable: true,
  65494. configurable: true
  65495. });
  65496. /**
  65497. * Gets the camera which post process is applied to.
  65498. * @returns The camera the post process is applied to.
  65499. */
  65500. PostProcess.prototype.getCamera = function () {
  65501. return this._camera;
  65502. };
  65503. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65504. /**
  65505. * Gets the texel size of the postprocess.
  65506. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65507. */
  65508. get: function () {
  65509. if (this._shareOutputWithPostProcess) {
  65510. return this._shareOutputWithPostProcess.texelSize;
  65511. }
  65512. if (this._forcedOutputTexture) {
  65513. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65514. }
  65515. return this._texelSize;
  65516. },
  65517. enumerable: true,
  65518. configurable: true
  65519. });
  65520. /**
  65521. * Gets the engine which this post process belongs to.
  65522. * @returns The engine the post process was enabled with.
  65523. */
  65524. PostProcess.prototype.getEngine = function () {
  65525. return this._engine;
  65526. };
  65527. /**
  65528. * The effect that is created when initializing the post process.
  65529. * @returns The created effect corrisponding the the postprocess.
  65530. */
  65531. PostProcess.prototype.getEffect = function () {
  65532. return this._effect;
  65533. };
  65534. /**
  65535. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65536. * @param postProcess The post process to share the output with.
  65537. * @returns This post process.
  65538. */
  65539. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65540. this._disposeTextures();
  65541. this._shareOutputWithPostProcess = postProcess;
  65542. return this;
  65543. };
  65544. /**
  65545. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65546. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65547. */
  65548. PostProcess.prototype.useOwnOutput = function () {
  65549. if (this._textures.length == 0) {
  65550. this._textures = new BABYLON.SmartArray(2);
  65551. }
  65552. this._shareOutputWithPostProcess = null;
  65553. };
  65554. /**
  65555. * Updates the effect with the current post process compile time values and recompiles the shader.
  65556. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65557. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65558. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65559. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  65560. * @param onCompiled Called when the shader has been compiled.
  65561. * @param onError Called if there is an error when compiling a shader.
  65562. */
  65563. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65564. if (defines === void 0) { defines = null; }
  65565. if (uniforms === void 0) { uniforms = null; }
  65566. if (samplers === void 0) { samplers = null; }
  65567. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== null ? defines : "", undefined, onCompiled, onError, indexParameters || this._indexParameters);
  65568. };
  65569. /**
  65570. * The post process is reusable if it can be used multiple times within one frame.
  65571. * @returns If the post process is reusable
  65572. */
  65573. PostProcess.prototype.isReusable = function () {
  65574. return this._reusable;
  65575. };
  65576. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65577. PostProcess.prototype.markTextureDirty = function () {
  65578. this.width = -1;
  65579. };
  65580. /**
  65581. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65582. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  65583. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65584. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65585. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65586. * @returns The target texture that was bound to be written to.
  65587. */
  65588. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65589. var _this = this;
  65590. if (sourceTexture === void 0) { sourceTexture = null; }
  65591. camera = camera || this._camera;
  65592. var scene = camera.getScene();
  65593. var engine = scene.getEngine();
  65594. var maxSize = engine.getCaps().maxTextureSize;
  65595. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65596. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65597. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  65598. var webVRCamera = camera.parent;
  65599. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65600. requiredWidth /= 2;
  65601. }
  65602. var desiredWidth = (this._options.width || requiredWidth);
  65603. var desiredHeight = this._options.height || requiredHeight;
  65604. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65605. if (this.adaptScaleToCurrentViewport) {
  65606. var currentViewport = engine.currentViewport;
  65607. if (currentViewport) {
  65608. desiredWidth *= currentViewport.width;
  65609. desiredHeight *= currentViewport.height;
  65610. }
  65611. }
  65612. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65613. if (!this._options.width) {
  65614. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65615. }
  65616. if (!this._options.height) {
  65617. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65618. }
  65619. }
  65620. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65621. if (this._textures.length > 0) {
  65622. for (var i = 0; i < this._textures.length; i++) {
  65623. this._engine._releaseTexture(this._textures.data[i]);
  65624. }
  65625. this._textures.reset();
  65626. }
  65627. this.width = desiredWidth;
  65628. this.height = desiredHeight;
  65629. var textureSize = { width: this.width, height: this.height };
  65630. var textureOptions = {
  65631. generateMipMaps: false,
  65632. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65633. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65634. samplingMode: this.renderTargetSamplingMode,
  65635. type: this._textureType
  65636. };
  65637. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65638. if (this._reusable) {
  65639. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65640. }
  65641. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65642. this.onSizeChangedObservable.notifyObservers(this);
  65643. }
  65644. this._textures.forEach(function (texture) {
  65645. if (texture.samples !== _this.samples) {
  65646. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65647. }
  65648. });
  65649. }
  65650. var target;
  65651. if (this._shareOutputWithPostProcess) {
  65652. target = this._shareOutputWithPostProcess.inputTexture;
  65653. }
  65654. else if (this._forcedOutputTexture) {
  65655. target = this._forcedOutputTexture;
  65656. this.width = this._forcedOutputTexture.width;
  65657. this.height = this._forcedOutputTexture.height;
  65658. }
  65659. else {
  65660. target = this.inputTexture;
  65661. }
  65662. // Bind the input of this post process to be used as the output of the previous post process.
  65663. if (this.enablePixelPerfectMode) {
  65664. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65665. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65666. }
  65667. else {
  65668. this._scaleRatio.copyFromFloats(1, 1);
  65669. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65670. }
  65671. this.onActivateObservable.notifyObservers(camera);
  65672. // Clear
  65673. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65674. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65675. }
  65676. if (this._reusable) {
  65677. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65678. }
  65679. return target;
  65680. };
  65681. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65682. /**
  65683. * If the post process is supported.
  65684. */
  65685. get: function () {
  65686. return this._effect.isSupported;
  65687. },
  65688. enumerable: true,
  65689. configurable: true
  65690. });
  65691. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65692. /**
  65693. * The aspect ratio of the output texture.
  65694. */
  65695. get: function () {
  65696. if (this._shareOutputWithPostProcess) {
  65697. return this._shareOutputWithPostProcess.aspectRatio;
  65698. }
  65699. if (this._forcedOutputTexture) {
  65700. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65701. }
  65702. return this.width / this.height;
  65703. },
  65704. enumerable: true,
  65705. configurable: true
  65706. });
  65707. /**
  65708. * Get a value indicating if the post-process is ready to be used
  65709. * @returns true if the post-process is ready (shader is compiled)
  65710. */
  65711. PostProcess.prototype.isReady = function () {
  65712. return this._effect && this._effect.isReady();
  65713. };
  65714. /**
  65715. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65716. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65717. */
  65718. PostProcess.prototype.apply = function () {
  65719. // Check
  65720. if (!this._effect || !this._effect.isReady())
  65721. return null;
  65722. // States
  65723. this._engine.enableEffect(this._effect);
  65724. this._engine.setState(false);
  65725. this._engine.setDepthBuffer(false);
  65726. this._engine.setDepthWrite(false);
  65727. // Alpha
  65728. this._engine.setAlphaMode(this.alphaMode);
  65729. if (this.alphaConstants) {
  65730. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65731. }
  65732. // Bind the output texture of the preivous post process as the input to this post process.
  65733. var source;
  65734. if (this._shareOutputWithPostProcess) {
  65735. source = this._shareOutputWithPostProcess.inputTexture;
  65736. }
  65737. else if (this._forcedOutputTexture) {
  65738. source = this._forcedOutputTexture;
  65739. }
  65740. else {
  65741. source = this.inputTexture;
  65742. }
  65743. this._effect._bindTexture("textureSampler", source);
  65744. // Parameters
  65745. this._effect.setVector2("scale", this._scaleRatio);
  65746. this.onApplyObservable.notifyObservers(this._effect);
  65747. return this._effect;
  65748. };
  65749. PostProcess.prototype._disposeTextures = function () {
  65750. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65751. return;
  65752. }
  65753. if (this._textures.length > 0) {
  65754. for (var i = 0; i < this._textures.length; i++) {
  65755. this._engine._releaseTexture(this._textures.data[i]);
  65756. }
  65757. }
  65758. this._textures.dispose();
  65759. };
  65760. /**
  65761. * Disposes the post process.
  65762. * @param camera The camera to dispose the post process on.
  65763. */
  65764. PostProcess.prototype.dispose = function (camera) {
  65765. camera = camera || this._camera;
  65766. this._disposeTextures();
  65767. if (this._scene) {
  65768. var index_1 = this._scene.postProcesses.indexOf(this);
  65769. if (index_1 !== -1) {
  65770. this._scene.postProcesses.splice(index_1, 1);
  65771. }
  65772. }
  65773. else {
  65774. var index_2 = this._engine.postProcesses.indexOf(this);
  65775. if (index_2 !== -1) {
  65776. this._engine.postProcesses.splice(index_2, 1);
  65777. }
  65778. }
  65779. if (!camera) {
  65780. return;
  65781. }
  65782. camera.detachPostProcess(this);
  65783. var index = camera._postProcesses.indexOf(this);
  65784. if (index === 0 && camera._postProcesses.length > 0) {
  65785. var firstPostProcess = this._camera._getFirstPostProcess();
  65786. if (firstPostProcess) {
  65787. firstPostProcess.markTextureDirty();
  65788. }
  65789. }
  65790. this.onActivateObservable.clear();
  65791. this.onAfterRenderObservable.clear();
  65792. this.onApplyObservable.clear();
  65793. this.onBeforeRenderObservable.clear();
  65794. this.onSizeChangedObservable.clear();
  65795. };
  65796. return PostProcess;
  65797. }());
  65798. BABYLON.PostProcess = PostProcess;
  65799. })(BABYLON || (BABYLON = {}));
  65800. //# sourceMappingURL=babylon.postProcess.js.map
  65801. var BABYLON;
  65802. (function (BABYLON) {
  65803. var PassPostProcess = /** @class */ (function (_super) {
  65804. __extends(PassPostProcess, _super);
  65805. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65806. if (camera === void 0) { camera = null; }
  65807. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65808. if (blockCompilation === void 0) { blockCompilation = false; }
  65809. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65810. }
  65811. return PassPostProcess;
  65812. }(BABYLON.PostProcess));
  65813. BABYLON.PassPostProcess = PassPostProcess;
  65814. })(BABYLON || (BABYLON = {}));
  65815. //# sourceMappingURL=babylon.passPostProcess.js.map
  65816. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65817. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65818. s = arguments[i];
  65819. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65820. t[p] = s[p];
  65821. }
  65822. return t;
  65823. };
  65824. var BABYLON;
  65825. (function (BABYLON) {
  65826. /**
  65827. * Default implementation IShadowGenerator.
  65828. * This is the main object responsible of generating shadows in the framework.
  65829. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65830. */
  65831. var ShadowGenerator = /** @class */ (function () {
  65832. /**
  65833. * Creates a ShadowGenerator object.
  65834. * A ShadowGenerator is the required tool to use the shadows.
  65835. * Each light casting shadows needs to use its own ShadowGenerator.
  65836. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65837. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65838. * @param light The light object generating the shadows.
  65839. * @param 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.
  65840. */
  65841. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65842. this._bias = 0.00005;
  65843. this._normalBias = 0;
  65844. this._blurBoxOffset = 1;
  65845. this._blurScale = 2;
  65846. this._blurKernel = 1;
  65847. this._useKernelBlur = false;
  65848. this._filter = ShadowGenerator.FILTER_NONE;
  65849. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65850. this._contactHardeningLightSizeUVRatio = 0.1;
  65851. this._darkness = 0;
  65852. this._transparencyShadow = false;
  65853. /**
  65854. * Controls the extent to which the shadows fade out at the edge of the frustum
  65855. * Used only by directionals and spots
  65856. */
  65857. this.frustumEdgeFalloff = 0;
  65858. /**
  65859. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65860. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65861. * It might on the other hand introduce peter panning.
  65862. */
  65863. this.forceBackFacesOnly = false;
  65864. this._lightDirection = BABYLON.Vector3.Zero();
  65865. this._viewMatrix = BABYLON.Matrix.Zero();
  65866. this._projectionMatrix = BABYLON.Matrix.Zero();
  65867. this._transformMatrix = BABYLON.Matrix.Zero();
  65868. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65869. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65870. this._currentFaceIndex = 0;
  65871. this._currentFaceIndexCache = 0;
  65872. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65873. this._mapSize = mapSize;
  65874. this._light = light;
  65875. this._scene = light.getScene();
  65876. light._shadowGenerator = this;
  65877. // Texture type fallback from float to int if not supported.
  65878. var caps = this._scene.getEngine().getCaps();
  65879. if (!useFullFloatFirst) {
  65880. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65881. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65882. }
  65883. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65884. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65885. }
  65886. else {
  65887. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65888. }
  65889. }
  65890. else {
  65891. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65892. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65893. }
  65894. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65895. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65896. }
  65897. else {
  65898. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65899. }
  65900. }
  65901. this._initializeGenerator();
  65902. this._applyFilterValues();
  65903. }
  65904. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65905. /**
  65906. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65907. */
  65908. get: function () {
  65909. return this._bias;
  65910. },
  65911. /**
  65912. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65913. */
  65914. set: function (bias) {
  65915. this._bias = bias;
  65916. },
  65917. enumerable: true,
  65918. configurable: true
  65919. });
  65920. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65921. /**
  65922. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65923. */
  65924. get: function () {
  65925. return this._normalBias;
  65926. },
  65927. /**
  65928. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65929. */
  65930. set: function (normalBias) {
  65931. this._normalBias = normalBias;
  65932. },
  65933. enumerable: true,
  65934. configurable: true
  65935. });
  65936. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65937. /**
  65938. * Gets the blur box offset: offset applied during the blur pass.
  65939. * Only usefull if useKernelBlur = false
  65940. */
  65941. get: function () {
  65942. return this._blurBoxOffset;
  65943. },
  65944. /**
  65945. * Sets the blur box offset: offset applied during the blur pass.
  65946. * Only usefull if useKernelBlur = false
  65947. */
  65948. set: function (value) {
  65949. if (this._blurBoxOffset === value) {
  65950. return;
  65951. }
  65952. this._blurBoxOffset = value;
  65953. this._disposeBlurPostProcesses();
  65954. },
  65955. enumerable: true,
  65956. configurable: true
  65957. });
  65958. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65959. /**
  65960. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65961. * 2 means half of the size.
  65962. */
  65963. get: function () {
  65964. return this._blurScale;
  65965. },
  65966. /**
  65967. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65968. * 2 means half of the size.
  65969. */
  65970. set: function (value) {
  65971. if (this._blurScale === value) {
  65972. return;
  65973. }
  65974. this._blurScale = value;
  65975. this._disposeBlurPostProcesses();
  65976. },
  65977. enumerable: true,
  65978. configurable: true
  65979. });
  65980. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65981. /**
  65982. * Gets the blur kernel: kernel size of the blur pass.
  65983. * Only usefull if useKernelBlur = true
  65984. */
  65985. get: function () {
  65986. return this._blurKernel;
  65987. },
  65988. /**
  65989. * Sets the blur kernel: kernel size of the blur pass.
  65990. * Only usefull if useKernelBlur = true
  65991. */
  65992. set: function (value) {
  65993. if (this._blurKernel === value) {
  65994. return;
  65995. }
  65996. this._blurKernel = value;
  65997. this._disposeBlurPostProcesses();
  65998. },
  65999. enumerable: true,
  66000. configurable: true
  66001. });
  66002. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66003. /**
  66004. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66005. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66006. */
  66007. get: function () {
  66008. return this._useKernelBlur;
  66009. },
  66010. /**
  66011. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66012. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66013. */
  66014. set: function (value) {
  66015. if (this._useKernelBlur === value) {
  66016. return;
  66017. }
  66018. this._useKernelBlur = value;
  66019. this._disposeBlurPostProcesses();
  66020. },
  66021. enumerable: true,
  66022. configurable: true
  66023. });
  66024. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66025. /**
  66026. * Gets the depth scale used in ESM mode.
  66027. */
  66028. get: function () {
  66029. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66030. },
  66031. /**
  66032. * Sets the depth scale used in ESM mode.
  66033. * This can override the scale stored on the light.
  66034. */
  66035. set: function (value) {
  66036. this._depthScale = value;
  66037. },
  66038. enumerable: true,
  66039. configurable: true
  66040. });
  66041. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66042. /**
  66043. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66044. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66045. */
  66046. get: function () {
  66047. return this._filter;
  66048. },
  66049. /**
  66050. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66051. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66052. */
  66053. set: function (value) {
  66054. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66055. if (this._light.needCube()) {
  66056. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66057. this.useExponentialShadowMap = true;
  66058. return;
  66059. }
  66060. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66061. this.useCloseExponentialShadowMap = true;
  66062. return;
  66063. }
  66064. // PCF on cubemap would also be expensive
  66065. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66066. this.usePoissonSampling = true;
  66067. return;
  66068. }
  66069. }
  66070. // Weblg1 fallback for PCF.
  66071. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66072. if (this._scene.getEngine().webGLVersion === 1) {
  66073. this.usePoissonSampling = true;
  66074. return;
  66075. }
  66076. }
  66077. if (this._filter === value) {
  66078. return;
  66079. }
  66080. this._filter = value;
  66081. this._disposeBlurPostProcesses();
  66082. this._applyFilterValues();
  66083. this._light._markMeshesAsLightDirty();
  66084. },
  66085. enumerable: true,
  66086. configurable: true
  66087. });
  66088. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66089. /**
  66090. * Gets if the current filter is set to Poisson Sampling.
  66091. */
  66092. get: function () {
  66093. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66094. },
  66095. /**
  66096. * Sets the current filter to Poisson Sampling.
  66097. */
  66098. set: function (value) {
  66099. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66100. return;
  66101. }
  66102. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66103. },
  66104. enumerable: true,
  66105. configurable: true
  66106. });
  66107. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66108. /**
  66109. * Gets if the current filter is set to VSM.
  66110. * DEPRECATED. Should use useExponentialShadowMap instead.
  66111. */
  66112. get: function () {
  66113. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66114. return this.useExponentialShadowMap;
  66115. },
  66116. /**
  66117. * Sets the current filter is to VSM.
  66118. * DEPRECATED. Should use useExponentialShadowMap instead.
  66119. */
  66120. set: function (value) {
  66121. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66122. this.useExponentialShadowMap = value;
  66123. },
  66124. enumerable: true,
  66125. configurable: true
  66126. });
  66127. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66128. /**
  66129. * Gets if the current filter is set to blurred VSM.
  66130. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66131. */
  66132. get: function () {
  66133. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66134. return this.useBlurExponentialShadowMap;
  66135. },
  66136. /**
  66137. * Sets the current filter is to blurred VSM.
  66138. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66139. */
  66140. set: function (value) {
  66141. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66142. this.useBlurExponentialShadowMap = value;
  66143. },
  66144. enumerable: true,
  66145. configurable: true
  66146. });
  66147. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66148. /**
  66149. * Gets if the current filter is set to ESM.
  66150. */
  66151. get: function () {
  66152. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66153. },
  66154. /**
  66155. * Sets the current filter is to ESM.
  66156. */
  66157. set: function (value) {
  66158. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66159. return;
  66160. }
  66161. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66162. },
  66163. enumerable: true,
  66164. configurable: true
  66165. });
  66166. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66167. /**
  66168. * Gets if the current filter is set to filtered ESM.
  66169. */
  66170. get: function () {
  66171. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66172. },
  66173. /**
  66174. * Gets if the current filter is set to filtered ESM.
  66175. */
  66176. set: function (value) {
  66177. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66178. return;
  66179. }
  66180. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66181. },
  66182. enumerable: true,
  66183. configurable: true
  66184. });
  66185. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66186. /**
  66187. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66188. * exponential to prevent steep falloff artifacts).
  66189. */
  66190. get: function () {
  66191. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66192. },
  66193. /**
  66194. * Sets the current filter to "close ESM" (using the inverse of the
  66195. * exponential to prevent steep falloff artifacts).
  66196. */
  66197. set: function (value) {
  66198. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66199. return;
  66200. }
  66201. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66202. },
  66203. enumerable: true,
  66204. configurable: true
  66205. });
  66206. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66207. /**
  66208. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66209. * exponential to prevent steep falloff artifacts).
  66210. */
  66211. get: function () {
  66212. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66213. },
  66214. /**
  66215. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66216. * exponential to prevent steep falloff artifacts).
  66217. */
  66218. set: function (value) {
  66219. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66220. return;
  66221. }
  66222. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66223. },
  66224. enumerable: true,
  66225. configurable: true
  66226. });
  66227. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66228. /**
  66229. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66230. */
  66231. get: function () {
  66232. return this.filter === ShadowGenerator.FILTER_PCF;
  66233. },
  66234. /**
  66235. * Sets the current filter to "PCF" (percentage closer filtering).
  66236. */
  66237. set: function (value) {
  66238. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66239. return;
  66240. }
  66241. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66242. },
  66243. enumerable: true,
  66244. configurable: true
  66245. });
  66246. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66247. /**
  66248. * Gets the PCF or PCSS Quality.
  66249. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66250. */
  66251. get: function () {
  66252. return this._filteringQuality;
  66253. },
  66254. /**
  66255. * Sets the PCF or PCSS Quality.
  66256. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66257. */
  66258. set: function (filteringQuality) {
  66259. this._filteringQuality = filteringQuality;
  66260. },
  66261. enumerable: true,
  66262. configurable: true
  66263. });
  66264. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66265. /**
  66266. * Gets if the current filter is set to "PCSS" (contact hardening).
  66267. */
  66268. get: function () {
  66269. return this.filter === ShadowGenerator.FILTER_PCSS;
  66270. },
  66271. /**
  66272. * Sets the current filter to "PCSS" (contact hardening).
  66273. */
  66274. set: function (value) {
  66275. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66276. return;
  66277. }
  66278. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66279. },
  66280. enumerable: true,
  66281. configurable: true
  66282. });
  66283. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66284. /**
  66285. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66286. * Using a ratio helps keeping shape stability independently of the map size.
  66287. *
  66288. * It does not account for the light projection as it was having too much
  66289. * instability during the light setup or during light position changes.
  66290. *
  66291. * Only valid if useContactHardeningShadow is true.
  66292. */
  66293. get: function () {
  66294. return this._contactHardeningLightSizeUVRatio;
  66295. },
  66296. /**
  66297. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66298. * Using a ratio helps keeping shape stability independently of the map size.
  66299. *
  66300. * It does not account for the light projection as it was having too much
  66301. * instability during the light setup or during light position changes.
  66302. *
  66303. * Only valid if useContactHardeningShadow is true.
  66304. */
  66305. set: function (contactHardeningLightSizeUVRatio) {
  66306. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66307. },
  66308. enumerable: true,
  66309. configurable: true
  66310. });
  66311. /**
  66312. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66313. * 0 means strongest and 1 would means no shadow.
  66314. * @returns the darkness.
  66315. */
  66316. ShadowGenerator.prototype.getDarkness = function () {
  66317. return this._darkness;
  66318. };
  66319. /**
  66320. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66321. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66322. * @returns the shadow generator allowing fluent coding.
  66323. */
  66324. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66325. if (darkness >= 1.0)
  66326. this._darkness = 1.0;
  66327. else if (darkness <= 0.0)
  66328. this._darkness = 0.0;
  66329. else
  66330. this._darkness = darkness;
  66331. return this;
  66332. };
  66333. /**
  66334. * Sets the ability to have transparent shadow (boolean).
  66335. * @param transparent True if transparent else False
  66336. * @returns the shadow generator allowing fluent coding
  66337. */
  66338. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66339. this._transparencyShadow = transparent;
  66340. return this;
  66341. };
  66342. /**
  66343. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66344. * @returns The render target texture if present otherwise, null
  66345. */
  66346. ShadowGenerator.prototype.getShadowMap = function () {
  66347. return this._shadowMap;
  66348. };
  66349. /**
  66350. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66351. * @returns The render target texture if the shadow map is present otherwise, null
  66352. */
  66353. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66354. if (this._shadowMap2) {
  66355. return this._shadowMap2;
  66356. }
  66357. return this._shadowMap;
  66358. };
  66359. /**
  66360. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66361. * @param mesh Mesh to add
  66362. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66363. * @returns the Shadow Generator itself
  66364. */
  66365. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66366. if (includeDescendants === void 0) { includeDescendants = true; }
  66367. if (!this._shadowMap) {
  66368. return this;
  66369. }
  66370. if (!this._shadowMap.renderList) {
  66371. this._shadowMap.renderList = [];
  66372. }
  66373. this._shadowMap.renderList.push(mesh);
  66374. if (includeDescendants) {
  66375. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66376. }
  66377. return this;
  66378. var _a;
  66379. };
  66380. /**
  66381. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66382. * @param mesh Mesh to remove
  66383. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66384. * @returns the Shadow Generator itself
  66385. */
  66386. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66387. if (includeDescendants === void 0) { includeDescendants = true; }
  66388. if (!this._shadowMap || !this._shadowMap.renderList) {
  66389. return this;
  66390. }
  66391. var index = this._shadowMap.renderList.indexOf(mesh);
  66392. if (index !== -1) {
  66393. this._shadowMap.renderList.splice(index, 1);
  66394. }
  66395. if (includeDescendants) {
  66396. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66397. var child = _a[_i];
  66398. this.removeShadowCaster(child);
  66399. }
  66400. }
  66401. return this;
  66402. };
  66403. /**
  66404. * Returns the associated light object.
  66405. * @returns the light generating the shadow
  66406. */
  66407. ShadowGenerator.prototype.getLight = function () {
  66408. return this._light;
  66409. };
  66410. ShadowGenerator.prototype._initializeGenerator = function () {
  66411. this._light._markMeshesAsLightDirty();
  66412. this._initializeShadowMap();
  66413. };
  66414. ShadowGenerator.prototype._initializeShadowMap = function () {
  66415. var _this = this;
  66416. // Render target
  66417. var engine = this._scene.getEngine();
  66418. if (engine.webGLVersion > 1) {
  66419. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66420. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66421. }
  66422. else {
  66423. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66424. }
  66425. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66426. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66427. this._shadowMap.anisotropicFilteringLevel = 1;
  66428. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66429. this._shadowMap.renderParticles = false;
  66430. this._shadowMap.ignoreCameraViewport = true;
  66431. // Record Face Index before render.
  66432. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66433. _this._currentFaceIndex = faceIndex;
  66434. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66435. engine.setColorWrite(false);
  66436. }
  66437. });
  66438. // Custom render function.
  66439. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66440. // Blur if required afer render.
  66441. this._shadowMap.onAfterUnbindObservable.add(function () {
  66442. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66443. engine.setColorWrite(true);
  66444. }
  66445. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66446. return;
  66447. }
  66448. var shadowMap = _this.getShadowMapForRendering();
  66449. if (shadowMap) {
  66450. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66451. }
  66452. });
  66453. // Clear according to the chosen filter.
  66454. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66455. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66456. this._shadowMap.onClearObservable.add(function (engine) {
  66457. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66458. engine.clear(clearOne, false, true, false);
  66459. }
  66460. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66461. engine.clear(clearZero, true, true, false);
  66462. }
  66463. else {
  66464. engine.clear(clearOne, true, true, false);
  66465. }
  66466. });
  66467. };
  66468. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66469. var _this = this;
  66470. var engine = this._scene.getEngine();
  66471. var targetSize = this._mapSize / this.blurScale;
  66472. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66473. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66474. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66475. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66476. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66477. }
  66478. if (this.useKernelBlur) {
  66479. 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);
  66480. this._kernelBlurXPostprocess.width = targetSize;
  66481. this._kernelBlurXPostprocess.height = targetSize;
  66482. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66483. effect.setTexture("textureSampler", _this._shadowMap);
  66484. });
  66485. 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);
  66486. this._kernelBlurXPostprocess.autoClear = false;
  66487. this._kernelBlurYPostprocess.autoClear = false;
  66488. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66489. this._kernelBlurXPostprocess.packedFloat = true;
  66490. this._kernelBlurYPostprocess.packedFloat = true;
  66491. }
  66492. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66493. }
  66494. else {
  66495. 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);
  66496. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66497. effect.setFloat2("screenSize", targetSize, targetSize);
  66498. effect.setTexture("textureSampler", _this._shadowMap);
  66499. });
  66500. this._boxBlurPostprocess.autoClear = false;
  66501. this._blurPostProcesses = [this._boxBlurPostprocess];
  66502. }
  66503. };
  66504. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66505. var index;
  66506. var engine = this._scene.getEngine();
  66507. if (depthOnlySubMeshes.length) {
  66508. engine.setColorWrite(false);
  66509. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66510. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66511. }
  66512. engine.setColorWrite(true);
  66513. }
  66514. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66515. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66516. }
  66517. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66518. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66519. }
  66520. if (this._transparencyShadow) {
  66521. for (index = 0; index < transparentSubMeshes.length; index++) {
  66522. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66523. }
  66524. }
  66525. };
  66526. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66527. var _this = this;
  66528. var mesh = subMesh.getRenderingMesh();
  66529. var scene = this._scene;
  66530. var engine = scene.getEngine();
  66531. var material = subMesh.getMaterial();
  66532. if (!material) {
  66533. return;
  66534. }
  66535. // Culling
  66536. engine.setState(material.backFaceCulling);
  66537. // Managing instances
  66538. var batch = mesh._getInstancesRenderList(subMesh._id);
  66539. if (batch.mustReturn) {
  66540. return;
  66541. }
  66542. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66543. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66544. engine.enableEffect(this._effect);
  66545. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66546. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66547. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66548. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66549. this._effect.setVector3("lightData", this._cachedDirection);
  66550. }
  66551. else {
  66552. this._effect.setVector3("lightData", this._cachedPosition);
  66553. }
  66554. if (scene.activeCamera) {
  66555. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66556. }
  66557. // Alpha test
  66558. if (material && material.needAlphaTesting()) {
  66559. var alphaTexture = material.getAlphaTestTexture();
  66560. if (alphaTexture) {
  66561. this._effect.setTexture("diffuseSampler", alphaTexture);
  66562. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66563. }
  66564. }
  66565. // Bones
  66566. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66567. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66568. }
  66569. // Morph targets
  66570. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66571. if (this.forceBackFacesOnly) {
  66572. engine.setState(true, 0, false, true);
  66573. }
  66574. // Draw
  66575. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66576. if (this.forceBackFacesOnly) {
  66577. engine.setState(true, 0, false, false);
  66578. }
  66579. }
  66580. else {
  66581. // Need to reset refresh rate of the shadowMap
  66582. if (this._shadowMap) {
  66583. this._shadowMap.resetRefreshCounter();
  66584. }
  66585. }
  66586. };
  66587. ShadowGenerator.prototype._applyFilterValues = function () {
  66588. if (!this._shadowMap) {
  66589. return;
  66590. }
  66591. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66592. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66593. }
  66594. else {
  66595. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66596. }
  66597. };
  66598. /**
  66599. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66600. * @param onCompiled Callback triggered at the and of the effects compilation
  66601. * @param options Sets of optional options forcing the compilation with different modes
  66602. */
  66603. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66604. var _this = this;
  66605. var localOptions = __assign({ useInstances: false }, options);
  66606. var shadowMap = this.getShadowMap();
  66607. if (!shadowMap) {
  66608. if (onCompiled) {
  66609. onCompiled(this);
  66610. }
  66611. return;
  66612. }
  66613. var renderList = shadowMap.renderList;
  66614. if (!renderList) {
  66615. if (onCompiled) {
  66616. onCompiled(this);
  66617. }
  66618. return;
  66619. }
  66620. var subMeshes = new Array();
  66621. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66622. var mesh = renderList_1[_i];
  66623. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66624. }
  66625. if (subMeshes.length === 0) {
  66626. if (onCompiled) {
  66627. onCompiled(this);
  66628. }
  66629. return;
  66630. }
  66631. var currentIndex = 0;
  66632. var checkReady = function () {
  66633. if (!_this._scene || !_this._scene.getEngine()) {
  66634. return;
  66635. }
  66636. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66637. currentIndex++;
  66638. if (currentIndex >= subMeshes.length) {
  66639. if (onCompiled) {
  66640. onCompiled(_this);
  66641. }
  66642. return;
  66643. }
  66644. }
  66645. setTimeout(checkReady, 16);
  66646. };
  66647. checkReady();
  66648. };
  66649. /**
  66650. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66651. * @param options Sets of optional options forcing the compilation with different modes
  66652. * @returns A promise that resolves when the compilation completes
  66653. */
  66654. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66655. var _this = this;
  66656. return new Promise(function (resolve) {
  66657. _this.forceCompilation(function () {
  66658. resolve();
  66659. }, options);
  66660. });
  66661. };
  66662. /**
  66663. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66664. * @param subMesh The submesh we want to render in the shadow map
  66665. * @param useInstances Defines wether will draw in the map using instances
  66666. * @returns true if ready otherwise, false
  66667. */
  66668. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66669. var defines = [];
  66670. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66671. defines.push("#define FLOAT");
  66672. }
  66673. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66674. defines.push("#define ESM");
  66675. }
  66676. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66677. defines.push("#define DEPTHTEXTURE");
  66678. }
  66679. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66680. var mesh = subMesh.getMesh();
  66681. var material = subMesh.getMaterial();
  66682. // Normal bias.
  66683. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66684. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66685. defines.push("#define NORMAL");
  66686. if (mesh.nonUniformScaling) {
  66687. defines.push("#define NONUNIFORMSCALING");
  66688. }
  66689. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66690. defines.push("#define DIRECTIONINLIGHTDATA");
  66691. }
  66692. }
  66693. // Alpha test
  66694. if (material && material.needAlphaTesting()) {
  66695. var alphaTexture = material.getAlphaTestTexture();
  66696. if (alphaTexture) {
  66697. defines.push("#define ALPHATEST");
  66698. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66699. attribs.push(BABYLON.VertexBuffer.UVKind);
  66700. defines.push("#define UV1");
  66701. }
  66702. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66703. if (alphaTexture.coordinatesIndex === 1) {
  66704. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66705. defines.push("#define UV2");
  66706. }
  66707. }
  66708. }
  66709. }
  66710. // Bones
  66711. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66712. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66713. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66714. if (mesh.numBoneInfluencers > 4) {
  66715. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66716. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66717. }
  66718. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66719. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66720. }
  66721. else {
  66722. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66723. }
  66724. // Morph targets
  66725. var manager = mesh.morphTargetManager;
  66726. var morphInfluencers = 0;
  66727. if (manager) {
  66728. if (manager.numInfluencers > 0) {
  66729. defines.push("#define MORPHTARGETS");
  66730. morphInfluencers = manager.numInfluencers;
  66731. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66732. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66733. }
  66734. }
  66735. // Instances
  66736. if (useInstances) {
  66737. defines.push("#define INSTANCES");
  66738. attribs.push("world0");
  66739. attribs.push("world1");
  66740. attribs.push("world2");
  66741. attribs.push("world3");
  66742. }
  66743. // Get correct effect
  66744. var join = defines.join("\n");
  66745. if (this._cachedDefines !== join) {
  66746. this._cachedDefines = join;
  66747. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66748. }
  66749. if (!this._effect.isReady()) {
  66750. return false;
  66751. }
  66752. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66753. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66754. this._initializeBlurRTTAndPostProcesses();
  66755. }
  66756. }
  66757. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66758. return false;
  66759. }
  66760. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66761. return false;
  66762. }
  66763. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66764. return false;
  66765. }
  66766. return true;
  66767. };
  66768. /**
  66769. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66770. * @param defines Defines of the material we want to update
  66771. * @param lightIndex Index of the light in the enabled light list of the material
  66772. */
  66773. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66774. var scene = this._scene;
  66775. var light = this._light;
  66776. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66777. return;
  66778. }
  66779. defines["SHADOW" + lightIndex] = true;
  66780. if (this.useContactHardeningShadow) {
  66781. defines["SHADOWPCSS" + lightIndex] = true;
  66782. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66783. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66784. }
  66785. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66786. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66787. }
  66788. // else default to high.
  66789. }
  66790. if (this.usePercentageCloserFiltering) {
  66791. defines["SHADOWPCF" + lightIndex] = true;
  66792. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66793. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66794. }
  66795. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66796. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66797. }
  66798. // else default to high.
  66799. }
  66800. else if (this.usePoissonSampling) {
  66801. defines["SHADOWPOISSON" + lightIndex] = true;
  66802. }
  66803. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66804. defines["SHADOWESM" + lightIndex] = true;
  66805. }
  66806. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66807. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66808. }
  66809. if (light.needCube()) {
  66810. defines["SHADOWCUBE" + lightIndex] = true;
  66811. }
  66812. };
  66813. /**
  66814. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66815. * defined in the generator but impacting the effect).
  66816. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66817. * @param effect The effect we are binfing the information for
  66818. */
  66819. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66820. var light = this._light;
  66821. var scene = this._scene;
  66822. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66823. return;
  66824. }
  66825. var camera = scene.activeCamera;
  66826. if (!camera) {
  66827. return;
  66828. }
  66829. var shadowMap = this.getShadowMap();
  66830. if (!shadowMap) {
  66831. return;
  66832. }
  66833. if (!light.needCube()) {
  66834. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66835. }
  66836. // Only PCF uses depth stencil texture.
  66837. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66838. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66839. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66840. }
  66841. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66842. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66843. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66844. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66845. }
  66846. else {
  66847. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66848. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66849. }
  66850. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66851. };
  66852. /**
  66853. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66854. * (eq to shadow prjection matrix * light transform matrix)
  66855. * @returns The transform matrix used to create the shadow map
  66856. */
  66857. ShadowGenerator.prototype.getTransformMatrix = function () {
  66858. var scene = this._scene;
  66859. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66860. return this._transformMatrix;
  66861. }
  66862. this._currentRenderID = scene.getRenderId();
  66863. this._currentFaceIndexCache = this._currentFaceIndex;
  66864. var lightPosition = this._light.position;
  66865. if (this._light.computeTransformedInformation()) {
  66866. lightPosition = this._light.transformedPosition;
  66867. }
  66868. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66869. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66870. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66871. }
  66872. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66873. this._cachedPosition.copyFrom(lightPosition);
  66874. this._cachedDirection.copyFrom(this._lightDirection);
  66875. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66876. var shadowMap = this.getShadowMap();
  66877. if (shadowMap) {
  66878. var renderList = shadowMap.renderList;
  66879. if (renderList) {
  66880. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66881. }
  66882. }
  66883. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66884. }
  66885. return this._transformMatrix;
  66886. };
  66887. /**
  66888. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66889. * Cube and 2D textures for instance.
  66890. */
  66891. ShadowGenerator.prototype.recreateShadowMap = function () {
  66892. var shadowMap = this._shadowMap;
  66893. if (!shadowMap) {
  66894. return;
  66895. }
  66896. // Track render list.
  66897. var renderList = shadowMap.renderList;
  66898. // Clean up existing data.
  66899. this._disposeRTTandPostProcesses();
  66900. // Reinitializes.
  66901. this._initializeGenerator();
  66902. // Reaffect the filter to ensure a correct fallback if necessary.
  66903. this.filter = this.filter;
  66904. // Reaffect the filter.
  66905. this._applyFilterValues();
  66906. // Reaffect Render List.
  66907. this._shadowMap.renderList = renderList;
  66908. };
  66909. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66910. if (this._shadowMap2) {
  66911. this._shadowMap2.dispose();
  66912. this._shadowMap2 = null;
  66913. }
  66914. if (this._boxBlurPostprocess) {
  66915. this._boxBlurPostprocess.dispose();
  66916. this._boxBlurPostprocess = null;
  66917. }
  66918. if (this._kernelBlurXPostprocess) {
  66919. this._kernelBlurXPostprocess.dispose();
  66920. this._kernelBlurXPostprocess = null;
  66921. }
  66922. if (this._kernelBlurYPostprocess) {
  66923. this._kernelBlurYPostprocess.dispose();
  66924. this._kernelBlurYPostprocess = null;
  66925. }
  66926. this._blurPostProcesses = [];
  66927. };
  66928. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66929. if (this._shadowMap) {
  66930. this._shadowMap.dispose();
  66931. this._shadowMap = null;
  66932. }
  66933. this._disposeBlurPostProcesses();
  66934. };
  66935. /**
  66936. * Disposes the ShadowGenerator.
  66937. * Returns nothing.
  66938. */
  66939. ShadowGenerator.prototype.dispose = function () {
  66940. this._disposeRTTandPostProcesses();
  66941. if (this._light) {
  66942. this._light._shadowGenerator = null;
  66943. this._light._markMeshesAsLightDirty();
  66944. }
  66945. };
  66946. /**
  66947. * Serializes the shadow generator setup to a json object.
  66948. * @returns The serialized JSON object
  66949. */
  66950. ShadowGenerator.prototype.serialize = function () {
  66951. var serializationObject = {};
  66952. var shadowMap = this.getShadowMap();
  66953. if (!shadowMap) {
  66954. return serializationObject;
  66955. }
  66956. serializationObject.lightId = this._light.id;
  66957. serializationObject.mapSize = shadowMap.getRenderSize();
  66958. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66959. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66960. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66961. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66962. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66963. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66964. serializationObject.depthScale = this.depthScale;
  66965. serializationObject.darkness = this.getDarkness();
  66966. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66967. serializationObject.blurKernel = this.blurKernel;
  66968. serializationObject.blurScale = this.blurScale;
  66969. serializationObject.useKernelBlur = this.useKernelBlur;
  66970. serializationObject.transparencyShadow = this._transparencyShadow;
  66971. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66972. serializationObject.bias = this.bias;
  66973. serializationObject.normalBias = this.normalBias;
  66974. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66975. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66976. serializationObject.filteringQuality = this.filteringQuality;
  66977. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66978. serializationObject.renderList = [];
  66979. if (shadowMap.renderList) {
  66980. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66981. var mesh = shadowMap.renderList[meshIndex];
  66982. serializationObject.renderList.push(mesh.id);
  66983. }
  66984. }
  66985. return serializationObject;
  66986. };
  66987. /**
  66988. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66989. * @param parsedShadowGenerator The JSON object to parse
  66990. * @param scene The scene to create the shadow map for
  66991. * @returns The parsed shadow generator
  66992. */
  66993. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66994. //casting to point light, as light is missing the position attr and typescript complains.
  66995. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66996. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66997. var shadowMap = shadowGenerator.getShadowMap();
  66998. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66999. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67000. meshes.forEach(function (mesh) {
  67001. if (!shadowMap) {
  67002. return;
  67003. }
  67004. if (!shadowMap.renderList) {
  67005. shadowMap.renderList = [];
  67006. }
  67007. shadowMap.renderList.push(mesh);
  67008. });
  67009. }
  67010. if (parsedShadowGenerator.usePoissonSampling) {
  67011. shadowGenerator.usePoissonSampling = true;
  67012. }
  67013. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67014. shadowGenerator.useExponentialShadowMap = true;
  67015. }
  67016. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67017. shadowGenerator.useBlurExponentialShadowMap = true;
  67018. }
  67019. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67020. shadowGenerator.useCloseExponentialShadowMap = true;
  67021. }
  67022. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67023. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67024. }
  67025. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67026. shadowGenerator.usePercentageCloserFiltering = true;
  67027. }
  67028. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67029. shadowGenerator.useContactHardeningShadow = true;
  67030. }
  67031. if (parsedShadowGenerator.filteringQuality) {
  67032. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67033. }
  67034. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67035. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67036. }
  67037. // Backward compat
  67038. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67039. shadowGenerator.useExponentialShadowMap = true;
  67040. }
  67041. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67042. shadowGenerator.useBlurExponentialShadowMap = true;
  67043. }
  67044. if (parsedShadowGenerator.depthScale) {
  67045. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67046. }
  67047. if (parsedShadowGenerator.blurScale) {
  67048. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67049. }
  67050. if (parsedShadowGenerator.blurBoxOffset) {
  67051. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67052. }
  67053. if (parsedShadowGenerator.useKernelBlur) {
  67054. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67055. }
  67056. if (parsedShadowGenerator.blurKernel) {
  67057. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67058. }
  67059. if (parsedShadowGenerator.bias !== undefined) {
  67060. shadowGenerator.bias = parsedShadowGenerator.bias;
  67061. }
  67062. if (parsedShadowGenerator.normalBias !== undefined) {
  67063. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67064. }
  67065. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67066. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67067. }
  67068. if (parsedShadowGenerator.darkness) {
  67069. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67070. }
  67071. if (parsedShadowGenerator.transparencyShadow) {
  67072. shadowGenerator.setTransparencyShadow(true);
  67073. }
  67074. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67075. return shadowGenerator;
  67076. };
  67077. /**
  67078. * Shadow generator mode None: no filtering applied.
  67079. */
  67080. ShadowGenerator.FILTER_NONE = 0;
  67081. /**
  67082. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67083. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67084. */
  67085. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67086. /**
  67087. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67088. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67089. */
  67090. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67091. /**
  67092. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67093. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67094. */
  67095. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67096. /**
  67097. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67098. * edge artifacts on steep falloff.
  67099. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67100. */
  67101. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67102. /**
  67103. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67104. * edge artifacts on steep falloff.
  67105. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67106. */
  67107. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67108. /**
  67109. * Shadow generator mode PCF: Percentage Closer Filtering
  67110. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67111. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67112. */
  67113. ShadowGenerator.FILTER_PCF = 6;
  67114. /**
  67115. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67116. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67117. * Contact Hardening
  67118. */
  67119. ShadowGenerator.FILTER_PCSS = 7;
  67120. /**
  67121. * Reserved for PCF and PCSS
  67122. * Highest Quality.
  67123. *
  67124. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67125. *
  67126. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67127. */
  67128. ShadowGenerator.QUALITY_HIGH = 0;
  67129. /**
  67130. * Reserved for PCF and PCSS
  67131. * Good tradeoff for quality/perf cross devices
  67132. *
  67133. * Execute PCF on a 3*3 kernel.
  67134. *
  67135. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67136. */
  67137. ShadowGenerator.QUALITY_MEDIUM = 1;
  67138. /**
  67139. * Reserved for PCF and PCSS
  67140. * The lowest quality but the fastest.
  67141. *
  67142. * Execute PCF on a 1*1 kernel.
  67143. *
  67144. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67145. */
  67146. ShadowGenerator.QUALITY_LOW = 2;
  67147. return ShadowGenerator;
  67148. }());
  67149. BABYLON.ShadowGenerator = ShadowGenerator;
  67150. })(BABYLON || (BABYLON = {}));
  67151. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67152. var BABYLON;
  67153. (function (BABYLON) {
  67154. var DefaultLoadingScreen = /** @class */ (function () {
  67155. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67156. if (_loadingText === void 0) { _loadingText = ""; }
  67157. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67158. var _this = this;
  67159. this._renderingCanvas = _renderingCanvas;
  67160. this._loadingText = _loadingText;
  67161. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67162. // Resize
  67163. this._resizeLoadingUI = function () {
  67164. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67165. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67166. if (!_this._loadingDiv) {
  67167. return;
  67168. }
  67169. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67170. _this._loadingDiv.style.left = canvasRect.left + "px";
  67171. _this._loadingDiv.style.top = canvasRect.top + "px";
  67172. _this._loadingDiv.style.width = canvasRect.width + "px";
  67173. _this._loadingDiv.style.height = canvasRect.height + "px";
  67174. };
  67175. }
  67176. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67177. if (this._loadingDiv) {
  67178. // Do not add a loading screen if there is already one
  67179. return;
  67180. }
  67181. this._loadingDiv = document.createElement("div");
  67182. this._loadingDiv.id = "babylonjsLoadingDiv";
  67183. this._loadingDiv.style.opacity = "0";
  67184. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67185. this._loadingDiv.style.pointerEvents = "none";
  67186. // Loading text
  67187. this._loadingTextDiv = document.createElement("div");
  67188. this._loadingTextDiv.style.position = "absolute";
  67189. this._loadingTextDiv.style.left = "0";
  67190. this._loadingTextDiv.style.top = "50%";
  67191. this._loadingTextDiv.style.marginTop = "80px";
  67192. this._loadingTextDiv.style.width = "100%";
  67193. this._loadingTextDiv.style.height = "20px";
  67194. this._loadingTextDiv.style.fontFamily = "Arial";
  67195. this._loadingTextDiv.style.fontSize = "14px";
  67196. this._loadingTextDiv.style.color = "white";
  67197. this._loadingTextDiv.style.textAlign = "center";
  67198. this._loadingTextDiv.innerHTML = "Loading";
  67199. this._loadingDiv.appendChild(this._loadingTextDiv);
  67200. //set the predefined text
  67201. this._loadingTextDiv.innerHTML = this._loadingText;
  67202. // Generating keyframes
  67203. var style = document.createElement('style');
  67204. style.type = 'text/css';
  67205. 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 }";
  67206. style.innerHTML = keyFrames;
  67207. document.getElementsByTagName('head')[0].appendChild(style);
  67208. // Loading img
  67209. var imgBack = new Image();
  67210. 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";
  67211. imgBack.style.position = "absolute";
  67212. imgBack.style.left = "50%";
  67213. imgBack.style.top = "50%";
  67214. imgBack.style.marginLeft = "-60px";
  67215. imgBack.style.marginTop = "-60px";
  67216. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67217. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67218. imgBack.style.transformOrigin = "50% 50%";
  67219. imgBack.style.webkitTransformOrigin = "50% 50%";
  67220. this._loadingDiv.appendChild(imgBack);
  67221. this._resizeLoadingUI();
  67222. window.addEventListener("resize", this._resizeLoadingUI);
  67223. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67224. document.body.appendChild(this._loadingDiv);
  67225. this._loadingDiv.style.opacity = "1";
  67226. };
  67227. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67228. var _this = this;
  67229. if (!this._loadingDiv) {
  67230. return;
  67231. }
  67232. var onTransitionEnd = function () {
  67233. if (!_this._loadingDiv) {
  67234. return;
  67235. }
  67236. document.body.removeChild(_this._loadingDiv);
  67237. window.removeEventListener("resize", _this._resizeLoadingUI);
  67238. _this._loadingDiv = null;
  67239. };
  67240. this._loadingDiv.style.opacity = "0";
  67241. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67242. };
  67243. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67244. set: function (text) {
  67245. this._loadingText = text;
  67246. if (this._loadingTextDiv) {
  67247. this._loadingTextDiv.innerHTML = this._loadingText;
  67248. }
  67249. },
  67250. enumerable: true,
  67251. configurable: true
  67252. });
  67253. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67254. get: function () {
  67255. return this._loadingDivBackgroundColor;
  67256. },
  67257. set: function (color) {
  67258. this._loadingDivBackgroundColor = color;
  67259. if (!this._loadingDiv) {
  67260. return;
  67261. }
  67262. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67263. },
  67264. enumerable: true,
  67265. configurable: true
  67266. });
  67267. return DefaultLoadingScreen;
  67268. }());
  67269. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67270. })(BABYLON || (BABYLON = {}));
  67271. //# sourceMappingURL=babylon.loadingScreen.js.map
  67272. var BABYLON;
  67273. (function (BABYLON) {
  67274. var SceneLoaderProgressEvent = /** @class */ (function () {
  67275. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67276. this.lengthComputable = lengthComputable;
  67277. this.loaded = loaded;
  67278. this.total = total;
  67279. }
  67280. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67281. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67282. };
  67283. return SceneLoaderProgressEvent;
  67284. }());
  67285. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67286. var SceneLoader = /** @class */ (function () {
  67287. function SceneLoader() {
  67288. }
  67289. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67290. get: function () {
  67291. return 0;
  67292. },
  67293. enumerable: true,
  67294. configurable: true
  67295. });
  67296. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67297. get: function () {
  67298. return 1;
  67299. },
  67300. enumerable: true,
  67301. configurable: true
  67302. });
  67303. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67304. get: function () {
  67305. return 2;
  67306. },
  67307. enumerable: true,
  67308. configurable: true
  67309. });
  67310. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67311. get: function () {
  67312. return 3;
  67313. },
  67314. enumerable: true,
  67315. configurable: true
  67316. });
  67317. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67318. get: function () {
  67319. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67320. },
  67321. set: function (value) {
  67322. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67323. },
  67324. enumerable: true,
  67325. configurable: true
  67326. });
  67327. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67328. get: function () {
  67329. return SceneLoader._ShowLoadingScreen;
  67330. },
  67331. set: function (value) {
  67332. SceneLoader._ShowLoadingScreen = value;
  67333. },
  67334. enumerable: true,
  67335. configurable: true
  67336. });
  67337. Object.defineProperty(SceneLoader, "loggingLevel", {
  67338. get: function () {
  67339. return SceneLoader._loggingLevel;
  67340. },
  67341. set: function (value) {
  67342. SceneLoader._loggingLevel = value;
  67343. },
  67344. enumerable: true,
  67345. configurable: true
  67346. });
  67347. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67348. get: function () {
  67349. return SceneLoader._CleanBoneMatrixWeights;
  67350. },
  67351. set: function (value) {
  67352. SceneLoader._CleanBoneMatrixWeights = value;
  67353. },
  67354. enumerable: true,
  67355. configurable: true
  67356. });
  67357. SceneLoader._getDefaultPlugin = function () {
  67358. return SceneLoader._registeredPlugins[".babylon"];
  67359. };
  67360. SceneLoader._getPluginForExtension = function (extension) {
  67361. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67362. if (registeredPlugin) {
  67363. return registeredPlugin;
  67364. }
  67365. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67366. return SceneLoader._getDefaultPlugin();
  67367. };
  67368. SceneLoader._getPluginForDirectLoad = function (data) {
  67369. for (var extension in SceneLoader._registeredPlugins) {
  67370. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67371. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67372. return SceneLoader._registeredPlugins[extension];
  67373. }
  67374. }
  67375. return SceneLoader._getDefaultPlugin();
  67376. };
  67377. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67378. if (sceneFilename.name) {
  67379. sceneFilename = sceneFilename.name;
  67380. }
  67381. var queryStringPosition = sceneFilename.indexOf("?");
  67382. if (queryStringPosition !== -1) {
  67383. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67384. }
  67385. var dotPosition = sceneFilename.lastIndexOf(".");
  67386. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67387. return SceneLoader._getPluginForExtension(extension);
  67388. };
  67389. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67390. SceneLoader._getDirectLoad = function (sceneFilename) {
  67391. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67392. return sceneFilename.substr(5);
  67393. }
  67394. return null;
  67395. };
  67396. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67397. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67398. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67399. var plugin;
  67400. if (registeredPlugin.plugin.createPlugin) {
  67401. plugin = registeredPlugin.plugin.createPlugin();
  67402. }
  67403. else {
  67404. plugin = registeredPlugin.plugin;
  67405. }
  67406. var useArrayBuffer = registeredPlugin.isBinary;
  67407. var database;
  67408. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67409. var dataCallback = function (data, responseURL) {
  67410. if (scene.isDisposed) {
  67411. onError("Scene has been disposed");
  67412. return;
  67413. }
  67414. scene.database = database;
  67415. onSuccess(plugin, data, responseURL);
  67416. };
  67417. var request = null;
  67418. var pluginDisposed = false;
  67419. var onDisposeObservable = plugin.onDisposeObservable;
  67420. if (onDisposeObservable) {
  67421. onDisposeObservable.add(function () {
  67422. pluginDisposed = true;
  67423. if (request) {
  67424. request.abort();
  67425. request = null;
  67426. }
  67427. onDispose();
  67428. });
  67429. }
  67430. var manifestChecked = function () {
  67431. if (pluginDisposed) {
  67432. return;
  67433. }
  67434. var url = rootUrl + sceneFilename;
  67435. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67436. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67437. } : undefined, database, useArrayBuffer, function (request, exception) {
  67438. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67439. });
  67440. };
  67441. if (directLoad) {
  67442. dataCallback(directLoad);
  67443. return plugin;
  67444. }
  67445. if (rootUrl.indexOf("file:") === -1) {
  67446. var engine = scene.getEngine();
  67447. var canUseOfflineSupport = engine.enableOfflineSupport;
  67448. if (canUseOfflineSupport) {
  67449. // Also check for exceptions
  67450. var exceptionFound = false;
  67451. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67452. var regex = _a[_i];
  67453. if (regex.test(rootUrl + sceneFilename)) {
  67454. exceptionFound = true;
  67455. break;
  67456. }
  67457. }
  67458. canUseOfflineSupport = !exceptionFound;
  67459. }
  67460. if (canUseOfflineSupport) {
  67461. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67462. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67463. }
  67464. else {
  67465. manifestChecked();
  67466. }
  67467. }
  67468. // Loading file from disk via input file or drag'n'drop
  67469. else {
  67470. var fileOrString = sceneFilename;
  67471. if (fileOrString.name) { // File
  67472. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67473. }
  67474. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67475. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67476. }
  67477. else {
  67478. onError("Unable to find file named " + sceneFilename);
  67479. }
  67480. }
  67481. return plugin;
  67482. };
  67483. // Public functions
  67484. SceneLoader.GetPluginForExtension = function (extension) {
  67485. return SceneLoader._getPluginForExtension(extension).plugin;
  67486. };
  67487. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67488. return !!SceneLoader._registeredPlugins[extension];
  67489. };
  67490. SceneLoader.RegisterPlugin = function (plugin) {
  67491. if (typeof plugin.extensions === "string") {
  67492. var extension = plugin.extensions;
  67493. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67494. plugin: plugin,
  67495. isBinary: false
  67496. };
  67497. }
  67498. else {
  67499. var extensions = plugin.extensions;
  67500. Object.keys(extensions).forEach(function (extension) {
  67501. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67502. plugin: plugin,
  67503. isBinary: extensions[extension].isBinary
  67504. };
  67505. });
  67506. }
  67507. };
  67508. /**
  67509. * Import meshes into a scene
  67510. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67511. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67512. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67513. * @param scene the instance of BABYLON.Scene to append to
  67514. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67515. * @param onProgress a callback with a progress event for each file being loaded
  67516. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67517. * @param pluginExtension the extension used to determine the plugin
  67518. * @returns The loaded plugin
  67519. */
  67520. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67521. if (sceneFilename === void 0) { sceneFilename = ""; }
  67522. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67523. if (onSuccess === void 0) { onSuccess = null; }
  67524. if (onProgress === void 0) { onProgress = null; }
  67525. if (onError === void 0) { onError = null; }
  67526. if (pluginExtension === void 0) { pluginExtension = null; }
  67527. if (!scene) {
  67528. BABYLON.Tools.Error("No scene available to import mesh to");
  67529. return null;
  67530. }
  67531. if (!sceneFilename) {
  67532. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67533. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67534. }
  67535. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67536. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67537. return null;
  67538. }
  67539. var loadingToken = {};
  67540. scene._addPendingData(loadingToken);
  67541. var disposeHandler = function () {
  67542. scene._removePendingData(loadingToken);
  67543. };
  67544. var errorHandler = function (message, exception) {
  67545. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67546. if (onError) {
  67547. onError(scene, errorMessage, exception);
  67548. }
  67549. else {
  67550. BABYLON.Tools.Error(errorMessage);
  67551. // should the exception be thrown?
  67552. }
  67553. disposeHandler();
  67554. };
  67555. var progressHandler = onProgress ? function (event) {
  67556. try {
  67557. onProgress(event);
  67558. }
  67559. catch (e) {
  67560. errorHandler("Error in onProgress callback", e);
  67561. }
  67562. } : undefined;
  67563. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67564. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67565. if (onSuccess) {
  67566. try {
  67567. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67568. }
  67569. catch (e) {
  67570. errorHandler("Error in onSuccess callback", e);
  67571. }
  67572. }
  67573. scene._removePendingData(loadingToken);
  67574. };
  67575. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67576. if (plugin.rewriteRootURL) {
  67577. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67578. }
  67579. if (sceneFilename === "") {
  67580. if (sceneFilename === "") {
  67581. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67582. }
  67583. }
  67584. if (plugin.importMesh) {
  67585. var syncedPlugin = plugin;
  67586. var meshes = new Array();
  67587. var particleSystems = new Array();
  67588. var skeletons = new Array();
  67589. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67590. return;
  67591. }
  67592. scene.loadingPluginName = plugin.name;
  67593. successHandler(meshes, particleSystems, skeletons, []);
  67594. }
  67595. else {
  67596. var asyncedPlugin = plugin;
  67597. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67598. scene.loadingPluginName = plugin.name;
  67599. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67600. }).catch(function (error) {
  67601. errorHandler(error.message, error);
  67602. });
  67603. }
  67604. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67605. };
  67606. /**
  67607. * Import meshes into a scene
  67608. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67609. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67610. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67611. * @param scene the instance of BABYLON.Scene to append to
  67612. * @param onProgress a callback with a progress event for each file being loaded
  67613. * @param pluginExtension the extension used to determine the plugin
  67614. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67615. */
  67616. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67617. if (sceneFilename === void 0) { sceneFilename = ""; }
  67618. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67619. if (onProgress === void 0) { onProgress = null; }
  67620. if (pluginExtension === void 0) { pluginExtension = null; }
  67621. return new Promise(function (resolve, reject) {
  67622. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67623. resolve({
  67624. meshes: meshes,
  67625. particleSystems: particleSystems,
  67626. skeletons: skeletons,
  67627. animationGroups: animationGroups
  67628. });
  67629. }, onProgress, function (scene, message, exception) {
  67630. reject(exception || new Error(message));
  67631. }, pluginExtension);
  67632. });
  67633. };
  67634. /**
  67635. * Load a scene
  67636. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67637. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67638. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67639. * @param onSuccess a callback with the scene when import succeeds
  67640. * @param onProgress a callback with a progress event for each file being loaded
  67641. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67642. * @param pluginExtension the extension used to determine the plugin
  67643. * @returns The loaded plugin
  67644. */
  67645. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67646. if (onSuccess === void 0) { onSuccess = null; }
  67647. if (onProgress === void 0) { onProgress = null; }
  67648. if (onError === void 0) { onError = null; }
  67649. if (pluginExtension === void 0) { pluginExtension = null; }
  67650. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67651. };
  67652. /**
  67653. * Load a scene
  67654. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67655. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67656. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67657. * @param onProgress a callback with a progress event for each file being loaded
  67658. * @param pluginExtension the extension used to determine the plugin
  67659. * @returns The loaded scene
  67660. */
  67661. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67662. if (onProgress === void 0) { onProgress = null; }
  67663. if (pluginExtension === void 0) { pluginExtension = null; }
  67664. return new Promise(function (resolve, reject) {
  67665. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67666. resolve(scene);
  67667. }, onProgress, function (scene, message, exception) {
  67668. reject(exception || new Error(message));
  67669. }, pluginExtension);
  67670. });
  67671. };
  67672. /**
  67673. * Append a scene
  67674. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67675. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67676. * @param scene is the instance of BABYLON.Scene to append to
  67677. * @param onSuccess a callback with the scene when import succeeds
  67678. * @param onProgress a callback with a progress event for each file being loaded
  67679. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67680. * @param pluginExtension the extension used to determine the plugin
  67681. * @returns The loaded plugin
  67682. */
  67683. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67684. if (sceneFilename === void 0) { sceneFilename = ""; }
  67685. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67686. if (onSuccess === void 0) { onSuccess = null; }
  67687. if (onProgress === void 0) { onProgress = null; }
  67688. if (onError === void 0) { onError = null; }
  67689. if (pluginExtension === void 0) { pluginExtension = null; }
  67690. if (!scene) {
  67691. BABYLON.Tools.Error("No scene available to append to");
  67692. return null;
  67693. }
  67694. if (!sceneFilename) {
  67695. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67696. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67697. }
  67698. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67699. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67700. return null;
  67701. }
  67702. if (SceneLoader.ShowLoadingScreen) {
  67703. scene.getEngine().displayLoadingUI();
  67704. }
  67705. var loadingToken = {};
  67706. scene._addPendingData(loadingToken);
  67707. var disposeHandler = function () {
  67708. scene._removePendingData(loadingToken);
  67709. scene.getEngine().hideLoadingUI();
  67710. };
  67711. var errorHandler = function (message, exception) {
  67712. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67713. if (onError) {
  67714. onError(scene, errorMessage, exception);
  67715. }
  67716. else {
  67717. BABYLON.Tools.Error(errorMessage);
  67718. // should the exception be thrown?
  67719. }
  67720. disposeHandler();
  67721. };
  67722. var progressHandler = onProgress ? function (event) {
  67723. try {
  67724. onProgress(event);
  67725. }
  67726. catch (e) {
  67727. errorHandler("Error in onProgress callback", e);
  67728. }
  67729. } : undefined;
  67730. var successHandler = function () {
  67731. if (onSuccess) {
  67732. try {
  67733. onSuccess(scene);
  67734. }
  67735. catch (e) {
  67736. errorHandler("Error in onSuccess callback", e);
  67737. }
  67738. }
  67739. scene._removePendingData(loadingToken);
  67740. };
  67741. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67742. if (sceneFilename === "") {
  67743. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67744. }
  67745. if (plugin.load) {
  67746. var syncedPlugin = plugin;
  67747. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67748. return;
  67749. }
  67750. scene.loadingPluginName = plugin.name;
  67751. successHandler();
  67752. }
  67753. else {
  67754. var asyncedPlugin = plugin;
  67755. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67756. scene.loadingPluginName = plugin.name;
  67757. successHandler();
  67758. }).catch(function (error) {
  67759. errorHandler(error.message, error);
  67760. });
  67761. }
  67762. if (SceneLoader.ShowLoadingScreen) {
  67763. scene.executeWhenReady(function () {
  67764. scene.getEngine().hideLoadingUI();
  67765. });
  67766. }
  67767. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67768. };
  67769. /**
  67770. * Append a scene
  67771. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67772. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67773. * @param scene is the instance of BABYLON.Scene to append to
  67774. * @param onProgress a callback with a progress event for each file being loaded
  67775. * @param pluginExtension the extension used to determine the plugin
  67776. * @returns The given scene
  67777. */
  67778. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67779. if (sceneFilename === void 0) { sceneFilename = ""; }
  67780. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67781. if (onProgress === void 0) { onProgress = null; }
  67782. if (pluginExtension === void 0) { pluginExtension = null; }
  67783. return new Promise(function (resolve, reject) {
  67784. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67785. resolve(scene);
  67786. }, onProgress, function (scene, message, exception) {
  67787. reject(exception || new Error(message));
  67788. }, pluginExtension);
  67789. });
  67790. };
  67791. /**
  67792. * Load a scene into an asset container
  67793. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67794. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67795. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67796. * @param onSuccess a callback with the scene when import succeeds
  67797. * @param onProgress a callback with a progress event for each file being loaded
  67798. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67799. * @param pluginExtension the extension used to determine the plugin
  67800. * @returns The loaded plugin
  67801. */
  67802. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67803. if (sceneFilename === void 0) { sceneFilename = ""; }
  67804. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67805. if (onSuccess === void 0) { onSuccess = null; }
  67806. if (onProgress === void 0) { onProgress = null; }
  67807. if (onError === void 0) { onError = null; }
  67808. if (pluginExtension === void 0) { pluginExtension = null; }
  67809. if (!scene) {
  67810. BABYLON.Tools.Error("No scene available to load asset container to");
  67811. return null;
  67812. }
  67813. if (!sceneFilename) {
  67814. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67815. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67816. }
  67817. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67818. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67819. return null;
  67820. }
  67821. var loadingToken = {};
  67822. scene._addPendingData(loadingToken);
  67823. var disposeHandler = function () {
  67824. scene._removePendingData(loadingToken);
  67825. };
  67826. var errorHandler = function (message, exception) {
  67827. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67828. if (onError) {
  67829. onError(scene, errorMessage, exception);
  67830. }
  67831. else {
  67832. BABYLON.Tools.Error(errorMessage);
  67833. // should the exception be thrown?
  67834. }
  67835. disposeHandler();
  67836. };
  67837. var progressHandler = onProgress ? function (event) {
  67838. try {
  67839. onProgress(event);
  67840. }
  67841. catch (e) {
  67842. errorHandler("Error in onProgress callback", e);
  67843. }
  67844. } : undefined;
  67845. var successHandler = function (assets) {
  67846. if (onSuccess) {
  67847. try {
  67848. onSuccess(assets);
  67849. }
  67850. catch (e) {
  67851. errorHandler("Error in onSuccess callback", e);
  67852. }
  67853. }
  67854. scene._removePendingData(loadingToken);
  67855. };
  67856. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67857. if (plugin.loadAssetContainer) {
  67858. var syncedPlugin = plugin;
  67859. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67860. if (!assetContainer) {
  67861. return;
  67862. }
  67863. scene.loadingPluginName = plugin.name;
  67864. successHandler(assetContainer);
  67865. }
  67866. else if (plugin.loadAssetContainerAsync) {
  67867. var asyncedPlugin = plugin;
  67868. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67869. scene.loadingPluginName = plugin.name;
  67870. successHandler(assetContainer);
  67871. }).catch(function (error) {
  67872. errorHandler(error.message, error);
  67873. });
  67874. }
  67875. else {
  67876. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67877. }
  67878. if (SceneLoader.ShowLoadingScreen) {
  67879. scene.executeWhenReady(function () {
  67880. scene.getEngine().hideLoadingUI();
  67881. });
  67882. }
  67883. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67884. };
  67885. /**
  67886. * Load a scene into an asset container
  67887. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67888. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67889. * @param scene is the instance of BABYLON.Scene to append to
  67890. * @param onProgress a callback with a progress event for each file being loaded
  67891. * @param pluginExtension the extension used to determine the plugin
  67892. * @returns The loaded asset container
  67893. */
  67894. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67895. if (sceneFilename === void 0) { sceneFilename = ""; }
  67896. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67897. if (onProgress === void 0) { onProgress = null; }
  67898. if (pluginExtension === void 0) { pluginExtension = null; }
  67899. return new Promise(function (resolve, reject) {
  67900. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67901. resolve(assetContainer);
  67902. }, onProgress, function (scene, message, exception) {
  67903. reject(exception || new Error(message));
  67904. }, pluginExtension);
  67905. });
  67906. };
  67907. // Flags
  67908. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67909. SceneLoader._ShowLoadingScreen = true;
  67910. SceneLoader._CleanBoneMatrixWeights = false;
  67911. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67912. // Members
  67913. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67914. SceneLoader._registeredPlugins = {};
  67915. return SceneLoader;
  67916. }());
  67917. BABYLON.SceneLoader = SceneLoader;
  67918. ;
  67919. })(BABYLON || (BABYLON = {}));
  67920. //# sourceMappingURL=babylon.sceneLoader.js.map
  67921. var BABYLON;
  67922. (function (BABYLON) {
  67923. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67924. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67925. var parsedMaterial = parsedData.materials[index];
  67926. if (parsedMaterial.id === id) {
  67927. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67928. }
  67929. }
  67930. return null;
  67931. };
  67932. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67933. for (var i in names) {
  67934. if (mesh.name === names[i]) {
  67935. hierarchyIds.push(mesh.id);
  67936. return true;
  67937. }
  67938. }
  67939. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67940. hierarchyIds.push(mesh.id);
  67941. return true;
  67942. }
  67943. return false;
  67944. };
  67945. var logOperation = function (operation, producer) {
  67946. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67947. };
  67948. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67949. if (addToScene === void 0) { addToScene = false; }
  67950. var container = new BABYLON.AssetContainer(scene);
  67951. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67952. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67953. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67954. // and avoid problems with multiple concurrent .babylon loads.
  67955. var log = "importScene has failed JSON parse";
  67956. try {
  67957. var parsedData = JSON.parse(data);
  67958. log = "";
  67959. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67960. var index;
  67961. var cache;
  67962. // Lights
  67963. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67964. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67965. var parsedLight = parsedData.lights[index];
  67966. var light = BABYLON.Light.Parse(parsedLight, scene);
  67967. if (light) {
  67968. container.lights.push(light);
  67969. log += (index === 0 ? "\n\tLights:" : "");
  67970. log += "\n\t\t" + light.toString(fullDetails);
  67971. }
  67972. }
  67973. }
  67974. // Animations
  67975. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67976. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67977. var parsedAnimation = parsedData.animations[index];
  67978. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67979. scene.animations.push(animation);
  67980. container.animations.push(animation);
  67981. log += (index === 0 ? "\n\tAnimations:" : "");
  67982. log += "\n\t\t" + animation.toString(fullDetails);
  67983. }
  67984. }
  67985. // Materials
  67986. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67987. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67988. var parsedMaterial = parsedData.materials[index];
  67989. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67990. container.materials.push(mat);
  67991. log += (index === 0 ? "\n\tMaterials:" : "");
  67992. log += "\n\t\t" + mat.toString(fullDetails);
  67993. }
  67994. }
  67995. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67996. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67997. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67998. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67999. container.multiMaterials.push(mmat);
  68000. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68001. log += "\n\t\t" + mmat.toString(fullDetails);
  68002. }
  68003. }
  68004. // Morph targets
  68005. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68006. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68007. var managerData = _a[_i];
  68008. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68009. }
  68010. }
  68011. // Skeletons
  68012. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68013. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68014. var parsedSkeleton = parsedData.skeletons[index];
  68015. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68016. container.skeletons.push(skeleton);
  68017. log += (index === 0 ? "\n\tSkeletons:" : "");
  68018. log += "\n\t\t" + skeleton.toString(fullDetails);
  68019. }
  68020. }
  68021. // Geometries
  68022. var geometries = parsedData.geometries;
  68023. if (geometries !== undefined && geometries !== null) {
  68024. var addedGeometry = new Array();
  68025. // Boxes
  68026. var boxes = geometries.boxes;
  68027. if (boxes !== undefined && boxes !== null) {
  68028. for (index = 0, cache = boxes.length; index < cache; index++) {
  68029. var parsedBox = boxes[index];
  68030. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68031. }
  68032. }
  68033. // Spheres
  68034. var spheres = geometries.spheres;
  68035. if (spheres !== undefined && spheres !== null) {
  68036. for (index = 0, cache = spheres.length; index < cache; index++) {
  68037. var parsedSphere = spheres[index];
  68038. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68039. }
  68040. }
  68041. // Cylinders
  68042. var cylinders = geometries.cylinders;
  68043. if (cylinders !== undefined && cylinders !== null) {
  68044. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68045. var parsedCylinder = cylinders[index];
  68046. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68047. }
  68048. }
  68049. // Toruses
  68050. var toruses = geometries.toruses;
  68051. if (toruses !== undefined && toruses !== null) {
  68052. for (index = 0, cache = toruses.length; index < cache; index++) {
  68053. var parsedTorus = toruses[index];
  68054. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68055. }
  68056. }
  68057. // Grounds
  68058. var grounds = geometries.grounds;
  68059. if (grounds !== undefined && grounds !== null) {
  68060. for (index = 0, cache = grounds.length; index < cache; index++) {
  68061. var parsedGround = grounds[index];
  68062. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68063. }
  68064. }
  68065. // Planes
  68066. var planes = geometries.planes;
  68067. if (planes !== undefined && planes !== null) {
  68068. for (index = 0, cache = planes.length; index < cache; index++) {
  68069. var parsedPlane = planes[index];
  68070. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68071. }
  68072. }
  68073. // TorusKnots
  68074. var torusKnots = geometries.torusKnots;
  68075. if (torusKnots !== undefined && torusKnots !== null) {
  68076. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68077. var parsedTorusKnot = torusKnots[index];
  68078. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68079. }
  68080. }
  68081. // VertexData
  68082. var vertexData = geometries.vertexData;
  68083. if (vertexData !== undefined && vertexData !== null) {
  68084. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68085. var parsedVertexData = vertexData[index];
  68086. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68087. }
  68088. }
  68089. addedGeometry.forEach(function (g) {
  68090. if (g) {
  68091. container.geometries.push(g);
  68092. }
  68093. });
  68094. }
  68095. // Transform nodes
  68096. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68097. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68098. var parsedTransformNode = parsedData.transformNodes[index];
  68099. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68100. container.transformNodes.push(node);
  68101. }
  68102. }
  68103. // Meshes
  68104. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68105. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68106. var parsedMesh = parsedData.meshes[index];
  68107. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68108. container.meshes.push(mesh);
  68109. log += (index === 0 ? "\n\tMeshes:" : "");
  68110. log += "\n\t\t" + mesh.toString(fullDetails);
  68111. }
  68112. }
  68113. // Cameras
  68114. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68115. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68116. var parsedCamera = parsedData.cameras[index];
  68117. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68118. container.cameras.push(camera);
  68119. log += (index === 0 ? "\n\tCameras:" : "");
  68120. log += "\n\t\t" + camera.toString(fullDetails);
  68121. }
  68122. }
  68123. // Browsing all the graph to connect the dots
  68124. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68125. var camera = scene.cameras[index];
  68126. if (camera._waitingParentId) {
  68127. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68128. camera._waitingParentId = null;
  68129. }
  68130. }
  68131. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68132. var light_1 = scene.lights[index];
  68133. if (light_1 && light_1._waitingParentId) {
  68134. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68135. light_1._waitingParentId = null;
  68136. }
  68137. }
  68138. // Sounds
  68139. // TODO: add sound
  68140. var loadedSounds = [];
  68141. var loadedSound;
  68142. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68143. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68144. var parsedSound = parsedData.sounds[index];
  68145. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68146. if (!parsedSound.url)
  68147. parsedSound.url = parsedSound.name;
  68148. if (!loadedSounds[parsedSound.url]) {
  68149. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68150. loadedSounds[parsedSound.url] = loadedSound;
  68151. container.sounds.push(loadedSound);
  68152. }
  68153. else {
  68154. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68155. }
  68156. }
  68157. else {
  68158. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68159. }
  68160. }
  68161. }
  68162. loadedSounds = [];
  68163. // Connect parents & children and parse actions
  68164. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68165. var transformNode = scene.transformNodes[index];
  68166. if (transformNode._waitingParentId) {
  68167. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68168. transformNode._waitingParentId = null;
  68169. }
  68170. }
  68171. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68172. var mesh = scene.meshes[index];
  68173. if (mesh._waitingParentId) {
  68174. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68175. mesh._waitingParentId = null;
  68176. }
  68177. if (mesh._waitingActions) {
  68178. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68179. mesh._waitingActions = null;
  68180. }
  68181. }
  68182. // freeze world matrix application
  68183. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68184. var currentMesh = scene.meshes[index];
  68185. if (currentMesh._waitingFreezeWorldMatrix) {
  68186. currentMesh.freezeWorldMatrix();
  68187. currentMesh._waitingFreezeWorldMatrix = null;
  68188. }
  68189. else {
  68190. currentMesh.computeWorldMatrix(true);
  68191. }
  68192. }
  68193. // Particles Systems
  68194. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68195. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68196. var parsedParticleSystem = parsedData.particleSystems[index];
  68197. if (parsedParticleSystem.activeParticleCount) {
  68198. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68199. container.particleSystems.push(ps);
  68200. }
  68201. else {
  68202. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68203. container.particleSystems.push(ps);
  68204. }
  68205. }
  68206. }
  68207. // Shadows
  68208. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68209. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68210. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68211. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68212. // SG would be available on their associated lights
  68213. }
  68214. }
  68215. // Lights exclusions / inclusions
  68216. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68217. var light_2 = scene.lights[index];
  68218. // Excluded check
  68219. if (light_2._excludedMeshesIds.length > 0) {
  68220. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68221. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68222. if (excludedMesh) {
  68223. light_2.excludedMeshes.push(excludedMesh);
  68224. }
  68225. }
  68226. light_2._excludedMeshesIds = [];
  68227. }
  68228. // Included check
  68229. if (light_2._includedOnlyMeshesIds.length > 0) {
  68230. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68231. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68232. if (includedOnlyMesh) {
  68233. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68234. }
  68235. }
  68236. light_2._includedOnlyMeshesIds = [];
  68237. }
  68238. }
  68239. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  68240. // Actions (scene)
  68241. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68242. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68243. }
  68244. if (!addToScene) {
  68245. container.removeAllFromScene();
  68246. }
  68247. }
  68248. catch (err) {
  68249. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68250. if (onError) {
  68251. onError(msg, err);
  68252. }
  68253. else {
  68254. BABYLON.Tools.Log(msg);
  68255. throw err;
  68256. }
  68257. }
  68258. finally {
  68259. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68260. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68261. }
  68262. }
  68263. return container;
  68264. };
  68265. BABYLON.SceneLoader.RegisterPlugin({
  68266. name: "babylon.js",
  68267. extensions: ".babylon",
  68268. canDirectLoad: function (data) {
  68269. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68270. return true;
  68271. }
  68272. return false;
  68273. },
  68274. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68275. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68276. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68277. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68278. // and avoid problems with multiple concurrent .babylon loads.
  68279. var log = "importMesh has failed JSON parse";
  68280. try {
  68281. var parsedData = JSON.parse(data);
  68282. log = "";
  68283. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68284. if (!meshesNames) {
  68285. meshesNames = null;
  68286. }
  68287. else if (!Array.isArray(meshesNames)) {
  68288. meshesNames = [meshesNames];
  68289. }
  68290. var hierarchyIds = new Array();
  68291. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68292. var loadedSkeletonsIds = [];
  68293. var loadedMaterialsIds = [];
  68294. var index;
  68295. var cache;
  68296. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68297. var parsedMesh = parsedData.meshes[index];
  68298. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68299. if (meshesNames !== null) {
  68300. // Remove found mesh name from list.
  68301. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68302. }
  68303. //Geometry?
  68304. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68305. //does the file contain geometries?
  68306. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68307. //find the correct geometry and add it to the scene
  68308. var found = false;
  68309. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68310. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68311. return;
  68312. }
  68313. else {
  68314. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68315. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68316. switch (geometryType) {
  68317. case "boxes":
  68318. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68319. break;
  68320. case "spheres":
  68321. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68322. break;
  68323. case "cylinders":
  68324. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68325. break;
  68326. case "toruses":
  68327. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68328. break;
  68329. case "grounds":
  68330. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68331. break;
  68332. case "planes":
  68333. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68334. break;
  68335. case "torusKnots":
  68336. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68337. break;
  68338. case "vertexData":
  68339. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68340. break;
  68341. }
  68342. found = true;
  68343. }
  68344. });
  68345. }
  68346. });
  68347. if (found === false) {
  68348. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68349. }
  68350. }
  68351. }
  68352. // Material ?
  68353. if (parsedMesh.materialId) {
  68354. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68355. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68356. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68357. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68358. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68359. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68360. var subMatId = parsedMultiMaterial.materials[matIndex];
  68361. loadedMaterialsIds.push(subMatId);
  68362. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68363. if (mat) {
  68364. log += "\n\tMaterial " + mat.toString(fullDetails);
  68365. }
  68366. }
  68367. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68368. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68369. if (mmat) {
  68370. materialFound = true;
  68371. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68372. }
  68373. break;
  68374. }
  68375. }
  68376. }
  68377. if (materialFound === false) {
  68378. loadedMaterialsIds.push(parsedMesh.materialId);
  68379. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68380. if (!mat) {
  68381. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68382. }
  68383. else {
  68384. log += "\n\tMaterial " + mat.toString(fullDetails);
  68385. }
  68386. }
  68387. }
  68388. // Skeleton ?
  68389. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68390. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68391. if (skeletonAlreadyLoaded === false) {
  68392. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68393. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68394. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68395. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68396. skeletons.push(skeleton);
  68397. loadedSkeletonsIds.push(parsedSkeleton.id);
  68398. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68399. }
  68400. }
  68401. }
  68402. }
  68403. // Morph targets ?
  68404. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68405. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68406. var managerData = _a[_i];
  68407. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68408. }
  68409. }
  68410. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68411. meshes.push(mesh);
  68412. log += "\n\tMesh " + mesh.toString(fullDetails);
  68413. }
  68414. }
  68415. // Connecting parents
  68416. var currentMesh;
  68417. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68418. currentMesh = scene.meshes[index];
  68419. if (currentMesh._waitingParentId) {
  68420. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68421. currentMesh._waitingParentId = null;
  68422. }
  68423. }
  68424. // freeze and compute world matrix application
  68425. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68426. currentMesh = scene.meshes[index];
  68427. if (currentMesh._waitingFreezeWorldMatrix) {
  68428. currentMesh.freezeWorldMatrix();
  68429. currentMesh._waitingFreezeWorldMatrix = null;
  68430. }
  68431. else {
  68432. currentMesh.computeWorldMatrix(true);
  68433. }
  68434. }
  68435. }
  68436. // Particles
  68437. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68438. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68439. var parsedParticleSystem = parsedData.particleSystems[index];
  68440. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68441. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68442. }
  68443. }
  68444. }
  68445. return true;
  68446. }
  68447. catch (err) {
  68448. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68449. if (onError) {
  68450. onError(msg, err);
  68451. }
  68452. else {
  68453. BABYLON.Tools.Log(msg);
  68454. throw err;
  68455. }
  68456. }
  68457. finally {
  68458. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68459. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68460. }
  68461. }
  68462. return false;
  68463. },
  68464. load: function (scene, data, rootUrl, onError) {
  68465. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68466. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68467. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68468. // and avoid problems with multiple concurrent .babylon loads.
  68469. var log = "importScene has failed JSON parse";
  68470. try {
  68471. var parsedData = JSON.parse(data);
  68472. log = "";
  68473. // Scene
  68474. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68475. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68476. }
  68477. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68478. scene.autoClear = parsedData.autoClear;
  68479. }
  68480. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68481. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68482. }
  68483. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68484. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68485. }
  68486. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68487. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68488. }
  68489. // Fog
  68490. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68491. scene.fogMode = parsedData.fogMode;
  68492. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68493. scene.fogStart = parsedData.fogStart;
  68494. scene.fogEnd = parsedData.fogEnd;
  68495. scene.fogDensity = parsedData.fogDensity;
  68496. log += "\tFog mode for scene: ";
  68497. switch (scene.fogMode) {
  68498. // getters not compiling, so using hardcoded
  68499. case 1:
  68500. log += "exp\n";
  68501. break;
  68502. case 2:
  68503. log += "exp2\n";
  68504. break;
  68505. case 3:
  68506. log += "linear\n";
  68507. break;
  68508. }
  68509. }
  68510. //Physics
  68511. if (parsedData.physicsEnabled) {
  68512. var physicsPlugin;
  68513. if (parsedData.physicsEngine === "cannon") {
  68514. physicsPlugin = new BABYLON.CannonJSPlugin();
  68515. }
  68516. else if (parsedData.physicsEngine === "oimo") {
  68517. physicsPlugin = new BABYLON.OimoJSPlugin();
  68518. }
  68519. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68520. //else - default engine, which is currently oimo
  68521. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68522. scene.enablePhysics(physicsGravity, physicsPlugin);
  68523. }
  68524. // Metadata
  68525. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68526. scene.metadata = parsedData.metadata;
  68527. }
  68528. //collisions, if defined. otherwise, default is true
  68529. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68530. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68531. }
  68532. scene.workerCollisions = !!parsedData.workerCollisions;
  68533. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68534. if (!container) {
  68535. return false;
  68536. }
  68537. if (parsedData.autoAnimate) {
  68538. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68539. }
  68540. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68541. scene.setActiveCameraByID(parsedData.activeCameraID);
  68542. }
  68543. // Environment texture
  68544. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68545. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68546. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68547. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68548. if (parsedData.environmentTextureRotationY) {
  68549. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68550. }
  68551. scene.environmentTexture = hdrTexture;
  68552. }
  68553. else {
  68554. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68555. if (parsedData.environmentTextureRotationY) {
  68556. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68557. }
  68558. scene.environmentTexture = cubeTexture;
  68559. }
  68560. if (parsedData.createDefaultSkybox === true) {
  68561. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68562. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68563. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68564. }
  68565. }
  68566. // Finish
  68567. return true;
  68568. }
  68569. catch (err) {
  68570. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68571. if (onError) {
  68572. onError(msg, err);
  68573. }
  68574. else {
  68575. BABYLON.Tools.Log(msg);
  68576. throw err;
  68577. }
  68578. }
  68579. finally {
  68580. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68581. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68582. }
  68583. }
  68584. return false;
  68585. },
  68586. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68587. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68588. return container;
  68589. }
  68590. });
  68591. })(BABYLON || (BABYLON = {}));
  68592. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68593. var BABYLON;
  68594. (function (BABYLON) {
  68595. var FilesInput = /** @class */ (function () {
  68596. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68597. this.onProcessFileCallback = function () { return true; };
  68598. this._engine = engine;
  68599. this._currentScene = scene;
  68600. this._sceneLoadedCallback = sceneLoadedCallback;
  68601. this._progressCallback = progressCallback;
  68602. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68603. this._textureLoadingCallback = textureLoadingCallback;
  68604. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68605. this._onReloadCallback = onReloadCallback;
  68606. this._errorCallback = errorCallback;
  68607. }
  68608. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68609. var _this = this;
  68610. if (elementToMonitor) {
  68611. this._elementToMonitor = elementToMonitor;
  68612. this._dragEnterHandler = function (e) { _this.drag(e); };
  68613. this._dragOverHandler = function (e) { _this.drag(e); };
  68614. this._dropHandler = function (e) { _this.drop(e); };
  68615. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68616. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68617. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68618. }
  68619. };
  68620. FilesInput.prototype.dispose = function () {
  68621. if (!this._elementToMonitor) {
  68622. return;
  68623. }
  68624. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68625. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68626. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68627. };
  68628. FilesInput.prototype.renderFunction = function () {
  68629. if (this._additionalRenderLoopLogicCallback) {
  68630. this._additionalRenderLoopLogicCallback();
  68631. }
  68632. if (this._currentScene) {
  68633. if (this._textureLoadingCallback) {
  68634. var remaining = this._currentScene.getWaitingItemsCount();
  68635. if (remaining > 0) {
  68636. this._textureLoadingCallback(remaining);
  68637. }
  68638. }
  68639. this._currentScene.render();
  68640. }
  68641. };
  68642. FilesInput.prototype.drag = function (e) {
  68643. e.stopPropagation();
  68644. e.preventDefault();
  68645. };
  68646. FilesInput.prototype.drop = function (eventDrop) {
  68647. eventDrop.stopPropagation();
  68648. eventDrop.preventDefault();
  68649. this.loadFiles(eventDrop);
  68650. };
  68651. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68652. var _this = this;
  68653. var reader = folder.createReader();
  68654. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68655. reader.readEntries(function (entries) {
  68656. remaining.count += entries.length;
  68657. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68658. var entry = entries_1[_i];
  68659. if (entry.isFile) {
  68660. entry.file(function (file) {
  68661. file.correctName = relativePath + file.name;
  68662. files.push(file);
  68663. if (--remaining.count === 0) {
  68664. callback();
  68665. }
  68666. });
  68667. }
  68668. else if (entry.isDirectory) {
  68669. _this._traverseFolder(entry, files, remaining, callback);
  68670. }
  68671. }
  68672. if (--remaining.count) {
  68673. callback();
  68674. }
  68675. });
  68676. };
  68677. FilesInput.prototype._processFiles = function (files) {
  68678. for (var i = 0; i < files.length; i++) {
  68679. var name = files[i].correctName.toLowerCase();
  68680. var extension = name.split('.').pop();
  68681. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68682. continue;
  68683. }
  68684. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68685. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68686. this._sceneFileToLoad = files[i];
  68687. }
  68688. else {
  68689. FilesInput.FilesToLoad[name] = files[i];
  68690. }
  68691. }
  68692. };
  68693. FilesInput.prototype.loadFiles = function (event) {
  68694. var _this = this;
  68695. if (this._startingProcessingFilesCallback)
  68696. this._startingProcessingFilesCallback();
  68697. // Handling data transfer via drag'n'drop
  68698. if (event && event.dataTransfer && event.dataTransfer.files) {
  68699. this._filesToLoad = event.dataTransfer.files;
  68700. }
  68701. // Handling files from input files
  68702. if (event && event.target && event.target.files) {
  68703. this._filesToLoad = event.target.files;
  68704. }
  68705. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68706. var files_1 = new Array();
  68707. var folders = [];
  68708. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68709. for (var i = 0; i < this._filesToLoad.length; i++) {
  68710. var fileToLoad = this._filesToLoad[i];
  68711. var name_1 = fileToLoad.name.toLowerCase();
  68712. var entry = void 0;
  68713. fileToLoad.correctName = name_1;
  68714. if (items) {
  68715. var item = items[i];
  68716. if (item.getAsEntry) {
  68717. entry = item.getAsEntry();
  68718. }
  68719. else if (item.webkitGetAsEntry) {
  68720. entry = item.webkitGetAsEntry();
  68721. }
  68722. }
  68723. if (!entry) {
  68724. files_1.push(fileToLoad);
  68725. }
  68726. else {
  68727. if (entry.isDirectory) {
  68728. folders.push(entry);
  68729. }
  68730. else {
  68731. files_1.push(fileToLoad);
  68732. }
  68733. }
  68734. }
  68735. if (folders.length === 0) {
  68736. this._processFiles(files_1);
  68737. this._processReload();
  68738. }
  68739. else {
  68740. var remaining = { count: folders.length };
  68741. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68742. var folder = folders_1[_i];
  68743. this._traverseFolder(folder, files_1, remaining, function () {
  68744. _this._processFiles(files_1);
  68745. if (remaining.count === 0) {
  68746. _this._processReload();
  68747. }
  68748. });
  68749. }
  68750. }
  68751. }
  68752. };
  68753. FilesInput.prototype._processReload = function () {
  68754. if (this._onReloadCallback) {
  68755. this._onReloadCallback(this._sceneFileToLoad);
  68756. }
  68757. else {
  68758. this.reload();
  68759. }
  68760. };
  68761. FilesInput.prototype.reload = function () {
  68762. var _this = this;
  68763. // If a scene file has been provided
  68764. if (this._sceneFileToLoad) {
  68765. if (this._currentScene) {
  68766. if (BABYLON.Tools.errorsCount > 0) {
  68767. BABYLON.Tools.ClearLogCache();
  68768. }
  68769. this._engine.stopRenderLoop();
  68770. }
  68771. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68772. if (_this._progressCallback) {
  68773. _this._progressCallback(progress);
  68774. }
  68775. }).then(function (scene) {
  68776. if (_this._currentScene) {
  68777. _this._currentScene.dispose();
  68778. }
  68779. _this._currentScene = scene;
  68780. if (_this._sceneLoadedCallback) {
  68781. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68782. }
  68783. // Wait for textures and shaders to be ready
  68784. _this._currentScene.executeWhenReady(function () {
  68785. _this._engine.runRenderLoop(function () {
  68786. _this.renderFunction();
  68787. });
  68788. });
  68789. }).catch(function (error) {
  68790. if (_this._errorCallback) {
  68791. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68792. }
  68793. });
  68794. }
  68795. else {
  68796. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68797. }
  68798. };
  68799. FilesInput.FilesToLoad = {};
  68800. return FilesInput;
  68801. }());
  68802. BABYLON.FilesInput = FilesInput;
  68803. })(BABYLON || (BABYLON = {}));
  68804. //# sourceMappingURL=babylon.filesInput.js.map
  68805. var BABYLON;
  68806. (function (BABYLON) {
  68807. /**
  68808. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68809. * The underlying implementation relies on an associative array to ensure the best performances.
  68810. * The value can be anything including 'null' but except 'undefined'
  68811. */
  68812. var StringDictionary = /** @class */ (function () {
  68813. function StringDictionary() {
  68814. this._count = 0;
  68815. this._data = {};
  68816. }
  68817. /**
  68818. * This will clear this dictionary and copy the content from the 'source' one.
  68819. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68820. * @param source the dictionary to take the content from and copy to this dictionary
  68821. */
  68822. StringDictionary.prototype.copyFrom = function (source) {
  68823. var _this = this;
  68824. this.clear();
  68825. source.forEach(function (t, v) { return _this.add(t, v); });
  68826. };
  68827. /**
  68828. * Get a value based from its key
  68829. * @param key the given key to get the matching value from
  68830. * @return the value if found, otherwise undefined is returned
  68831. */
  68832. StringDictionary.prototype.get = function (key) {
  68833. var val = this._data[key];
  68834. if (val !== undefined) {
  68835. return val;
  68836. }
  68837. return undefined;
  68838. };
  68839. /**
  68840. * Get a value from its key or add it if it doesn't exist.
  68841. * This method will ensure you that a given key/data will be present in the dictionary.
  68842. * @param key the given key to get the matching value from
  68843. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68844. * The factory will only be invoked if there's no data for the given key.
  68845. * @return the value corresponding to the key.
  68846. */
  68847. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68848. var val = this.get(key);
  68849. if (val !== undefined) {
  68850. return val;
  68851. }
  68852. val = factory(key);
  68853. if (val) {
  68854. this.add(key, val);
  68855. }
  68856. return val;
  68857. };
  68858. /**
  68859. * Get a value from its key if present in the dictionary otherwise add it
  68860. * @param key the key to get the value from
  68861. * @param val if there's no such key/value pair in the dictionary add it with this value
  68862. * @return the value corresponding to the key
  68863. */
  68864. StringDictionary.prototype.getOrAdd = function (key, val) {
  68865. var curVal = this.get(key);
  68866. if (curVal !== undefined) {
  68867. return curVal;
  68868. }
  68869. this.add(key, val);
  68870. return val;
  68871. };
  68872. /**
  68873. * Check if there's a given key in the dictionary
  68874. * @param key the key to check for
  68875. * @return true if the key is present, false otherwise
  68876. */
  68877. StringDictionary.prototype.contains = function (key) {
  68878. return this._data[key] !== undefined;
  68879. };
  68880. /**
  68881. * Add a new key and its corresponding value
  68882. * @param key the key to add
  68883. * @param value the value corresponding to the key
  68884. * @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
  68885. */
  68886. StringDictionary.prototype.add = function (key, value) {
  68887. if (this._data[key] !== undefined) {
  68888. return false;
  68889. }
  68890. this._data[key] = value;
  68891. ++this._count;
  68892. return true;
  68893. };
  68894. StringDictionary.prototype.set = function (key, value) {
  68895. if (this._data[key] === undefined) {
  68896. return false;
  68897. }
  68898. this._data[key] = value;
  68899. return true;
  68900. };
  68901. /**
  68902. * Get the element of the given key and remove it from the dictionary
  68903. * @param key
  68904. */
  68905. StringDictionary.prototype.getAndRemove = function (key) {
  68906. var val = this.get(key);
  68907. if (val !== undefined) {
  68908. delete this._data[key];
  68909. --this._count;
  68910. return val;
  68911. }
  68912. return null;
  68913. };
  68914. /**
  68915. * Remove a key/value from the dictionary.
  68916. * @param key the key to remove
  68917. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68918. */
  68919. StringDictionary.prototype.remove = function (key) {
  68920. if (this.contains(key)) {
  68921. delete this._data[key];
  68922. --this._count;
  68923. return true;
  68924. }
  68925. return false;
  68926. };
  68927. /**
  68928. * Clear the whole content of the dictionary
  68929. */
  68930. StringDictionary.prototype.clear = function () {
  68931. this._data = {};
  68932. this._count = 0;
  68933. };
  68934. Object.defineProperty(StringDictionary.prototype, "count", {
  68935. get: function () {
  68936. return this._count;
  68937. },
  68938. enumerable: true,
  68939. configurable: true
  68940. });
  68941. /**
  68942. * Execute a callback on each key/val of the dictionary.
  68943. * Note that you can remove any element in this dictionary in the callback implementation
  68944. * @param callback the callback to execute on a given key/value pair
  68945. */
  68946. StringDictionary.prototype.forEach = function (callback) {
  68947. for (var cur in this._data) {
  68948. var val = this._data[cur];
  68949. callback(cur, val);
  68950. }
  68951. };
  68952. /**
  68953. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68954. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68955. * Note that you can remove any element in this dictionary in the callback implementation
  68956. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68957. */
  68958. StringDictionary.prototype.first = function (callback) {
  68959. for (var cur in this._data) {
  68960. var val = this._data[cur];
  68961. var res = callback(cur, val);
  68962. if (res) {
  68963. return res;
  68964. }
  68965. }
  68966. return null;
  68967. };
  68968. return StringDictionary;
  68969. }());
  68970. BABYLON.StringDictionary = StringDictionary;
  68971. })(BABYLON || (BABYLON = {}));
  68972. //# sourceMappingURL=babylon.stringDictionary.js.map
  68973. var BABYLON;
  68974. (function (BABYLON) {
  68975. var Tags = /** @class */ (function () {
  68976. function Tags() {
  68977. }
  68978. Tags.EnableFor = function (obj) {
  68979. obj._tags = obj._tags || {};
  68980. obj.hasTags = function () {
  68981. return Tags.HasTags(obj);
  68982. };
  68983. obj.addTags = function (tagsString) {
  68984. return Tags.AddTagsTo(obj, tagsString);
  68985. };
  68986. obj.removeTags = function (tagsString) {
  68987. return Tags.RemoveTagsFrom(obj, tagsString);
  68988. };
  68989. obj.matchesTagsQuery = function (tagsQuery) {
  68990. return Tags.MatchesQuery(obj, tagsQuery);
  68991. };
  68992. };
  68993. Tags.DisableFor = function (obj) {
  68994. delete obj._tags;
  68995. delete obj.hasTags;
  68996. delete obj.addTags;
  68997. delete obj.removeTags;
  68998. delete obj.matchesTagsQuery;
  68999. };
  69000. Tags.HasTags = function (obj) {
  69001. if (!obj._tags) {
  69002. return false;
  69003. }
  69004. return !BABYLON.Tools.IsEmpty(obj._tags);
  69005. };
  69006. Tags.GetTags = function (obj, asString) {
  69007. if (asString === void 0) { asString = true; }
  69008. if (!obj._tags) {
  69009. return null;
  69010. }
  69011. if (asString) {
  69012. var tagsArray = [];
  69013. for (var tag in obj._tags) {
  69014. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69015. tagsArray.push(tag);
  69016. }
  69017. }
  69018. return tagsArray.join(" ");
  69019. }
  69020. else {
  69021. return obj._tags;
  69022. }
  69023. };
  69024. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69025. // a tag cannot start with '||', '&&', and '!'
  69026. // it cannot contain whitespaces
  69027. Tags.AddTagsTo = function (obj, tagsString) {
  69028. if (!tagsString) {
  69029. return;
  69030. }
  69031. if (typeof tagsString !== "string") {
  69032. return;
  69033. }
  69034. var tags = tagsString.split(" ");
  69035. tags.forEach(function (tag, index, array) {
  69036. Tags._AddTagTo(obj, tag);
  69037. });
  69038. };
  69039. Tags._AddTagTo = function (obj, tag) {
  69040. tag = tag.trim();
  69041. if (tag === "" || tag === "true" || tag === "false") {
  69042. return;
  69043. }
  69044. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69045. return;
  69046. }
  69047. Tags.EnableFor(obj);
  69048. obj._tags[tag] = true;
  69049. };
  69050. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69051. if (!Tags.HasTags(obj)) {
  69052. return;
  69053. }
  69054. var tags = tagsString.split(" ");
  69055. for (var t in tags) {
  69056. Tags._RemoveTagFrom(obj, tags[t]);
  69057. }
  69058. };
  69059. Tags._RemoveTagFrom = function (obj, tag) {
  69060. delete obj._tags[tag];
  69061. };
  69062. Tags.MatchesQuery = function (obj, tagsQuery) {
  69063. if (tagsQuery === undefined) {
  69064. return true;
  69065. }
  69066. if (tagsQuery === "") {
  69067. return Tags.HasTags(obj);
  69068. }
  69069. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69070. };
  69071. return Tags;
  69072. }());
  69073. BABYLON.Tags = Tags;
  69074. })(BABYLON || (BABYLON = {}));
  69075. //# sourceMappingURL=babylon.tags.js.map
  69076. var BABYLON;
  69077. (function (BABYLON) {
  69078. /**
  69079. * Class used to evalaute queries containing `and` and `or` operators
  69080. */
  69081. var AndOrNotEvaluator = /** @class */ (function () {
  69082. function AndOrNotEvaluator() {
  69083. }
  69084. /**
  69085. * Evaluate a query
  69086. * @param query defines the query to evaluate
  69087. * @param evaluateCallback defines the callback used to filter result
  69088. * @returns true if the query matches
  69089. */
  69090. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69091. if (!query.match(/\([^\(\)]*\)/g)) {
  69092. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69093. }
  69094. else {
  69095. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69096. // remove parenthesis
  69097. r = r.slice(1, r.length - 1);
  69098. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69099. });
  69100. }
  69101. if (query === "true") {
  69102. return true;
  69103. }
  69104. if (query === "false") {
  69105. return false;
  69106. }
  69107. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69108. };
  69109. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69110. evaluateCallback = evaluateCallback || (function (r) {
  69111. return r === "true" ? true : false;
  69112. });
  69113. var result;
  69114. var or = parenthesisContent.split("||");
  69115. for (var i in or) {
  69116. if (or.hasOwnProperty(i)) {
  69117. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69118. var and = ori.split("&&");
  69119. if (and.length > 1) {
  69120. for (var j = 0; j < and.length; ++j) {
  69121. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69122. if (andj !== "true" && andj !== "false") {
  69123. if (andj[0] === "!") {
  69124. result = !evaluateCallback(andj.substring(1));
  69125. }
  69126. else {
  69127. result = evaluateCallback(andj);
  69128. }
  69129. }
  69130. else {
  69131. result = andj === "true" ? true : false;
  69132. }
  69133. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69134. ori = "false";
  69135. break;
  69136. }
  69137. }
  69138. }
  69139. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69140. result = true;
  69141. break;
  69142. }
  69143. // result equals false (or undefined)
  69144. if (ori !== "true" && ori !== "false") {
  69145. if (ori[0] === "!") {
  69146. result = !evaluateCallback(ori.substring(1));
  69147. }
  69148. else {
  69149. result = evaluateCallback(ori);
  69150. }
  69151. }
  69152. else {
  69153. result = ori === "true" ? true : false;
  69154. }
  69155. }
  69156. }
  69157. // the whole parenthesis scope is replaced by 'true' or 'false'
  69158. return result ? "true" : "false";
  69159. };
  69160. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69161. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69162. // remove whitespaces
  69163. r = r.replace(/[\s]/g, function () { return ""; });
  69164. return r.length % 2 ? "!" : "";
  69165. });
  69166. booleanString = booleanString.trim();
  69167. if (booleanString === "!true") {
  69168. booleanString = "false";
  69169. }
  69170. else if (booleanString === "!false") {
  69171. booleanString = "true";
  69172. }
  69173. return booleanString;
  69174. };
  69175. return AndOrNotEvaluator;
  69176. }());
  69177. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69178. })(BABYLON || (BABYLON = {}));
  69179. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69180. var BABYLON;
  69181. (function (BABYLON) {
  69182. /**
  69183. * Class used to enable access to IndexedDB
  69184. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69185. */
  69186. var Database = /** @class */ (function () {
  69187. /**
  69188. * Creates a new Database
  69189. * @param urlToScene defines the url to load the scene
  69190. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69191. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69192. */
  69193. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69194. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69195. var _this = this;
  69196. // Handling various flavors of prefixed version of IndexedDB
  69197. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69198. this.callbackManifestChecked = callbackManifestChecked;
  69199. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69200. this.db = null;
  69201. this._enableSceneOffline = false;
  69202. this._enableTexturesOffline = false;
  69203. this.manifestVersionFound = 0;
  69204. this.mustUpdateRessources = false;
  69205. this.hasReachedQuota = false;
  69206. if (!Database.IDBStorageEnabled) {
  69207. this.callbackManifestChecked(true);
  69208. }
  69209. else {
  69210. if (disableManifestCheck) {
  69211. this._enableSceneOffline = true;
  69212. this._enableTexturesOffline = true;
  69213. this.manifestVersionFound = 1;
  69214. BABYLON.Tools.SetImmediate(function () {
  69215. _this.callbackManifestChecked(true);
  69216. });
  69217. }
  69218. else {
  69219. this._checkManifestFile();
  69220. }
  69221. }
  69222. }
  69223. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69224. /**
  69225. * Gets a boolean indicating if scene must be saved in the database
  69226. */
  69227. get: function () {
  69228. return this._enableSceneOffline;
  69229. },
  69230. enumerable: true,
  69231. configurable: true
  69232. });
  69233. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69234. /**
  69235. * Gets a boolean indicating if textures must be saved in the database
  69236. */
  69237. get: function () {
  69238. return this._enableTexturesOffline;
  69239. },
  69240. enumerable: true,
  69241. configurable: true
  69242. });
  69243. Database.prototype._checkManifestFile = function () {
  69244. var _this = this;
  69245. var noManifestFile = function () {
  69246. _this._enableSceneOffline = false;
  69247. _this._enableTexturesOffline = false;
  69248. _this.callbackManifestChecked(false);
  69249. };
  69250. var timeStampUsed = false;
  69251. var manifestURL = this.currentSceneUrl + ".manifest";
  69252. var xhr = new XMLHttpRequest();
  69253. if (navigator.onLine) {
  69254. // Adding a timestamp to by-pass browsers' cache
  69255. timeStampUsed = true;
  69256. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69257. }
  69258. xhr.open("GET", manifestURL, true);
  69259. xhr.addEventListener("load", function () {
  69260. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69261. try {
  69262. var manifestFile = JSON.parse(xhr.response);
  69263. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69264. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69265. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69266. _this.manifestVersionFound = manifestFile.version;
  69267. }
  69268. if (_this.callbackManifestChecked) {
  69269. _this.callbackManifestChecked(true);
  69270. }
  69271. }
  69272. catch (ex) {
  69273. noManifestFile();
  69274. }
  69275. }
  69276. else {
  69277. noManifestFile();
  69278. }
  69279. }, false);
  69280. xhr.addEventListener("error", function (event) {
  69281. if (timeStampUsed) {
  69282. timeStampUsed = false;
  69283. // Let's retry without the timeStamp
  69284. // It could fail when coupled with HTML5 Offline API
  69285. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69286. xhr.open("GET", retryManifestURL, true);
  69287. xhr.send();
  69288. }
  69289. else {
  69290. noManifestFile();
  69291. }
  69292. }, false);
  69293. try {
  69294. xhr.send();
  69295. }
  69296. catch (ex) {
  69297. BABYLON.Tools.Error("Error on XHR send request.");
  69298. this.callbackManifestChecked(false);
  69299. }
  69300. };
  69301. /**
  69302. * Open the database and make it available
  69303. * @param successCallback defines the callback to call on success
  69304. * @param errorCallback defines the callback to call on error
  69305. */
  69306. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69307. var _this = this;
  69308. var handleError = function () {
  69309. _this.isSupported = false;
  69310. if (errorCallback)
  69311. errorCallback();
  69312. };
  69313. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69314. // Your browser doesn't support IndexedDB
  69315. this.isSupported = false;
  69316. if (errorCallback)
  69317. errorCallback();
  69318. }
  69319. else {
  69320. // If the DB hasn't been opened or created yet
  69321. if (!this.db) {
  69322. this.hasReachedQuota = false;
  69323. this.isSupported = true;
  69324. var request = this.idbFactory.open("babylonjs", 1);
  69325. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69326. request.onerror = function (event) {
  69327. handleError();
  69328. };
  69329. // executes when a version change transaction cannot complete due to other active transactions
  69330. request.onblocked = function (event) {
  69331. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69332. handleError();
  69333. };
  69334. // DB has been opened successfully
  69335. request.onsuccess = function (event) {
  69336. _this.db = request.result;
  69337. successCallback();
  69338. };
  69339. // Initialization of the DB. Creating Scenes & Textures stores
  69340. request.onupgradeneeded = function (event) {
  69341. _this.db = (event.target).result;
  69342. if (_this.db) {
  69343. try {
  69344. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69345. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69346. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69347. }
  69348. catch (ex) {
  69349. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69350. handleError();
  69351. }
  69352. }
  69353. };
  69354. }
  69355. // DB has already been created and opened
  69356. else {
  69357. if (successCallback)
  69358. successCallback();
  69359. }
  69360. }
  69361. };
  69362. /**
  69363. * Loads an image from the database
  69364. * @param url defines the url to load from
  69365. * @param image defines the target DOM image
  69366. */
  69367. Database.prototype.loadImageFromDB = function (url, image) {
  69368. var _this = this;
  69369. var completeURL = Database._ReturnFullUrlLocation(url);
  69370. var saveAndLoadImage = function () {
  69371. if (!_this.hasReachedQuota && _this.db !== null) {
  69372. // the texture is not yet in the DB, let's try to save it
  69373. _this._saveImageIntoDBAsync(completeURL, image);
  69374. }
  69375. // If the texture is not in the DB and we've reached the DB quota limit
  69376. // let's load it directly from the web
  69377. else {
  69378. image.src = url;
  69379. }
  69380. };
  69381. if (!this.mustUpdateRessources) {
  69382. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69383. }
  69384. // First time we're download the images or update requested in the manifest file by a version change
  69385. else {
  69386. saveAndLoadImage();
  69387. }
  69388. };
  69389. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69390. if (this.isSupported && this.db !== null) {
  69391. var texture;
  69392. var transaction = this.db.transaction(["textures"]);
  69393. transaction.onabort = function (event) {
  69394. image.src = url;
  69395. };
  69396. transaction.oncomplete = function (event) {
  69397. var blobTextureURL;
  69398. if (texture) {
  69399. var URL = window.URL || window.webkitURL;
  69400. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69401. image.onerror = function () {
  69402. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69403. image.src = url;
  69404. };
  69405. image.src = blobTextureURL;
  69406. }
  69407. else {
  69408. notInDBCallback();
  69409. }
  69410. };
  69411. var getRequest = transaction.objectStore("textures").get(url);
  69412. getRequest.onsuccess = function (event) {
  69413. texture = (event.target).result;
  69414. };
  69415. getRequest.onerror = function (event) {
  69416. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69417. image.src = url;
  69418. };
  69419. }
  69420. else {
  69421. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69422. image.src = url;
  69423. }
  69424. };
  69425. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69426. var _this = this;
  69427. if (this.isSupported) {
  69428. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69429. var generateBlobUrl = function () {
  69430. var blobTextureURL;
  69431. if (blob) {
  69432. var URL = window.URL || window.webkitURL;
  69433. try {
  69434. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69435. }
  69436. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69437. catch (ex) {
  69438. blobTextureURL = URL.createObjectURL(blob);
  69439. }
  69440. }
  69441. if (blobTextureURL) {
  69442. image.src = blobTextureURL;
  69443. }
  69444. };
  69445. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69446. var xhr = new XMLHttpRequest(), blob;
  69447. xhr.open("GET", url, true);
  69448. xhr.responseType = "blob";
  69449. xhr.addEventListener("load", function () {
  69450. if (xhr.status === 200 && _this.db) {
  69451. // Blob as response (XHR2)
  69452. blob = xhr.response;
  69453. var transaction = _this.db.transaction(["textures"], "readwrite");
  69454. // the transaction could abort because of a QuotaExceededError error
  69455. transaction.onabort = function (event) {
  69456. try {
  69457. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69458. var srcElement = (event.srcElement || event.target);
  69459. var error = srcElement.error;
  69460. if (error && error.name === "QuotaExceededError") {
  69461. _this.hasReachedQuota = true;
  69462. }
  69463. }
  69464. catch (ex) { }
  69465. generateBlobUrl();
  69466. };
  69467. transaction.oncomplete = function (event) {
  69468. generateBlobUrl();
  69469. };
  69470. var newTexture = { textureUrl: url, data: blob };
  69471. try {
  69472. // Put the blob into the dabase
  69473. var addRequest = transaction.objectStore("textures").put(newTexture);
  69474. addRequest.onsuccess = function (event) {
  69475. };
  69476. addRequest.onerror = function (event) {
  69477. generateBlobUrl();
  69478. };
  69479. }
  69480. catch (ex) {
  69481. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69482. if (ex.code === 25) {
  69483. Database.IsUASupportingBlobStorage = false;
  69484. }
  69485. image.src = url;
  69486. }
  69487. }
  69488. else {
  69489. image.src = url;
  69490. }
  69491. }, false);
  69492. xhr.addEventListener("error", function (event) {
  69493. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69494. image.src = url;
  69495. }, false);
  69496. xhr.send();
  69497. }
  69498. else {
  69499. image.src = url;
  69500. }
  69501. }
  69502. else {
  69503. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69504. image.src = url;
  69505. }
  69506. };
  69507. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69508. var _this = this;
  69509. var updateVersion = function () {
  69510. // the version is not yet in the DB or we need to update it
  69511. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69512. };
  69513. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69514. };
  69515. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69516. var _this = this;
  69517. if (this.isSupported && this.db) {
  69518. var version;
  69519. try {
  69520. var transaction = this.db.transaction(["versions"]);
  69521. transaction.oncomplete = function (event) {
  69522. if (version) {
  69523. // If the version in the JSON file is different from the version in DB
  69524. if (_this.manifestVersionFound !== version.data) {
  69525. _this.mustUpdateRessources = true;
  69526. updateInDBCallback();
  69527. }
  69528. else {
  69529. callback(version.data);
  69530. }
  69531. }
  69532. // version was not found in DB
  69533. else {
  69534. _this.mustUpdateRessources = true;
  69535. updateInDBCallback();
  69536. }
  69537. };
  69538. transaction.onabort = function (event) {
  69539. callback(-1);
  69540. };
  69541. var getRequest = transaction.objectStore("versions").get(url);
  69542. getRequest.onsuccess = function (event) {
  69543. version = (event.target).result;
  69544. };
  69545. getRequest.onerror = function (event) {
  69546. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69547. callback(-1);
  69548. };
  69549. }
  69550. catch (ex) {
  69551. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69552. callback(-1);
  69553. }
  69554. }
  69555. else {
  69556. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69557. callback(-1);
  69558. }
  69559. };
  69560. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69561. var _this = this;
  69562. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69563. try {
  69564. // Open a transaction to the database
  69565. var transaction = this.db.transaction(["versions"], "readwrite");
  69566. // the transaction could abort because of a QuotaExceededError error
  69567. transaction.onabort = function (event) {
  69568. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69569. var error = event.srcElement['error'];
  69570. if (error && error.name === "QuotaExceededError") {
  69571. _this.hasReachedQuota = true;
  69572. }
  69573. }
  69574. catch (ex) { }
  69575. callback(-1);
  69576. };
  69577. transaction.oncomplete = function (event) {
  69578. callback(_this.manifestVersionFound);
  69579. };
  69580. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69581. // Put the scene into the database
  69582. var addRequest = transaction.objectStore("versions").put(newVersion);
  69583. addRequest.onsuccess = function (event) {
  69584. };
  69585. addRequest.onerror = function (event) {
  69586. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69587. };
  69588. }
  69589. catch (ex) {
  69590. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69591. callback(-1);
  69592. }
  69593. }
  69594. else {
  69595. callback(-1);
  69596. }
  69597. };
  69598. /**
  69599. * Loads a file from database
  69600. * @param url defines the URL to load from
  69601. * @param sceneLoaded defines a callback to call on success
  69602. * @param progressCallBack defines a callback to call when progress changed
  69603. * @param errorCallback defines a callback to call on error
  69604. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69605. */
  69606. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69607. var _this = this;
  69608. var completeUrl = Database._ReturnFullUrlLocation(url);
  69609. var saveAndLoadFile = function () {
  69610. // the scene is not yet in the DB, let's try to save it
  69611. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69612. };
  69613. this._checkVersionFromDB(completeUrl, function (version) {
  69614. if (version !== -1) {
  69615. if (!_this.mustUpdateRessources) {
  69616. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69617. }
  69618. else {
  69619. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69620. }
  69621. }
  69622. else {
  69623. if (errorCallback) {
  69624. errorCallback();
  69625. }
  69626. }
  69627. });
  69628. };
  69629. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69630. if (this.isSupported && this.db) {
  69631. var targetStore;
  69632. if (url.indexOf(".babylon") !== -1) {
  69633. targetStore = "scenes";
  69634. }
  69635. else {
  69636. targetStore = "textures";
  69637. }
  69638. var file;
  69639. var transaction = this.db.transaction([targetStore]);
  69640. transaction.oncomplete = function (event) {
  69641. if (file) {
  69642. callback(file.data);
  69643. }
  69644. // file was not found in DB
  69645. else {
  69646. notInDBCallback();
  69647. }
  69648. };
  69649. transaction.onabort = function (event) {
  69650. notInDBCallback();
  69651. };
  69652. var getRequest = transaction.objectStore(targetStore).get(url);
  69653. getRequest.onsuccess = function (event) {
  69654. file = (event.target).result;
  69655. };
  69656. getRequest.onerror = function (event) {
  69657. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69658. notInDBCallback();
  69659. };
  69660. }
  69661. else {
  69662. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69663. callback();
  69664. }
  69665. };
  69666. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69667. var _this = this;
  69668. if (this.isSupported) {
  69669. var targetStore;
  69670. if (url.indexOf(".babylon") !== -1) {
  69671. targetStore = "scenes";
  69672. }
  69673. else {
  69674. targetStore = "textures";
  69675. }
  69676. // Create XHR
  69677. var xhr = new XMLHttpRequest();
  69678. var fileData;
  69679. xhr.open("GET", url, true);
  69680. if (useArrayBuffer) {
  69681. xhr.responseType = "arraybuffer";
  69682. }
  69683. if (progressCallback) {
  69684. xhr.onprogress = progressCallback;
  69685. }
  69686. xhr.addEventListener("load", function () {
  69687. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69688. // Blob as response (XHR2)
  69689. //fileData = xhr.responseText;
  69690. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69691. if (!_this.hasReachedQuota && _this.db) {
  69692. // Open a transaction to the database
  69693. var transaction = _this.db.transaction([targetStore], "readwrite");
  69694. // the transaction could abort because of a QuotaExceededError error
  69695. transaction.onabort = function (event) {
  69696. try {
  69697. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69698. var error = event.srcElement['error'];
  69699. if (error && error.name === "QuotaExceededError") {
  69700. _this.hasReachedQuota = true;
  69701. }
  69702. }
  69703. catch (ex) { }
  69704. callback(fileData);
  69705. };
  69706. transaction.oncomplete = function (event) {
  69707. callback(fileData);
  69708. };
  69709. var newFile;
  69710. if (targetStore === "scenes") {
  69711. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69712. }
  69713. else {
  69714. newFile = { textureUrl: url, data: fileData };
  69715. }
  69716. try {
  69717. // Put the scene into the database
  69718. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69719. addRequest.onsuccess = function (event) {
  69720. };
  69721. addRequest.onerror = function (event) {
  69722. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69723. };
  69724. }
  69725. catch (ex) {
  69726. callback(fileData);
  69727. }
  69728. }
  69729. else {
  69730. callback(fileData);
  69731. }
  69732. }
  69733. else {
  69734. callback();
  69735. }
  69736. }, false);
  69737. xhr.addEventListener("error", function (event) {
  69738. BABYLON.Tools.Error("error on XHR request.");
  69739. callback();
  69740. }, false);
  69741. xhr.send();
  69742. }
  69743. else {
  69744. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69745. callback();
  69746. }
  69747. };
  69748. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69749. Database.IsUASupportingBlobStorage = true;
  69750. /** Gets a boolean indicating if Database storate is enabled */
  69751. Database.IDBStorageEnabled = true;
  69752. Database._ParseURL = function (url) {
  69753. var a = document.createElement('a');
  69754. a.href = url;
  69755. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69756. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69757. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69758. return absLocation;
  69759. };
  69760. Database._ReturnFullUrlLocation = function (url) {
  69761. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69762. return (Database._ParseURL(window.location.href) + url);
  69763. }
  69764. else {
  69765. return url;
  69766. }
  69767. };
  69768. return Database;
  69769. }());
  69770. BABYLON.Database = Database;
  69771. })(BABYLON || (BABYLON = {}));
  69772. //# sourceMappingURL=babylon.database.js.map
  69773. var BABYLON;
  69774. (function (BABYLON) {
  69775. var FresnelParameters = /** @class */ (function () {
  69776. function FresnelParameters() {
  69777. this._isEnabled = true;
  69778. this.leftColor = BABYLON.Color3.White();
  69779. this.rightColor = BABYLON.Color3.Black();
  69780. this.bias = 0;
  69781. this.power = 1;
  69782. }
  69783. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69784. get: function () {
  69785. return this._isEnabled;
  69786. },
  69787. set: function (value) {
  69788. if (this._isEnabled === value) {
  69789. return;
  69790. }
  69791. this._isEnabled = value;
  69792. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69793. },
  69794. enumerable: true,
  69795. configurable: true
  69796. });
  69797. FresnelParameters.prototype.clone = function () {
  69798. var newFresnelParameters = new FresnelParameters();
  69799. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69800. return newFresnelParameters;
  69801. };
  69802. FresnelParameters.prototype.serialize = function () {
  69803. var serializationObject = {};
  69804. serializationObject.isEnabled = this.isEnabled;
  69805. serializationObject.leftColor = this.leftColor.asArray();
  69806. serializationObject.rightColor = this.rightColor.asArray();
  69807. serializationObject.bias = this.bias;
  69808. serializationObject.power = this.power;
  69809. return serializationObject;
  69810. };
  69811. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69812. var fresnelParameters = new FresnelParameters();
  69813. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69814. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69815. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69816. fresnelParameters.bias = parsedFresnelParameters.bias;
  69817. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69818. return fresnelParameters;
  69819. };
  69820. return FresnelParameters;
  69821. }());
  69822. BABYLON.FresnelParameters = FresnelParameters;
  69823. })(BABYLON || (BABYLON = {}));
  69824. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69825. var BABYLON;
  69826. (function (BABYLON) {
  69827. var MultiMaterial = /** @class */ (function (_super) {
  69828. __extends(MultiMaterial, _super);
  69829. function MultiMaterial(name, scene) {
  69830. var _this = _super.call(this, name, scene, true) || this;
  69831. scene.multiMaterials.push(_this);
  69832. _this.subMaterials = new Array();
  69833. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69834. return _this;
  69835. }
  69836. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69837. get: function () {
  69838. return this._subMaterials;
  69839. },
  69840. set: function (value) {
  69841. this._subMaterials = value;
  69842. this._hookArray(value);
  69843. },
  69844. enumerable: true,
  69845. configurable: true
  69846. });
  69847. MultiMaterial.prototype._hookArray = function (array) {
  69848. var _this = this;
  69849. var oldPush = array.push;
  69850. array.push = function () {
  69851. var items = [];
  69852. for (var _i = 0; _i < arguments.length; _i++) {
  69853. items[_i] = arguments[_i];
  69854. }
  69855. var result = oldPush.apply(array, items);
  69856. _this._markAllSubMeshesAsTexturesDirty();
  69857. return result;
  69858. };
  69859. var oldSplice = array.splice;
  69860. array.splice = function (index, deleteCount) {
  69861. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69862. _this._markAllSubMeshesAsTexturesDirty();
  69863. return deleted;
  69864. };
  69865. };
  69866. // Properties
  69867. MultiMaterial.prototype.getSubMaterial = function (index) {
  69868. if (index < 0 || index >= this.subMaterials.length) {
  69869. return this.getScene().defaultMaterial;
  69870. }
  69871. return this.subMaterials[index];
  69872. };
  69873. MultiMaterial.prototype.getActiveTextures = function () {
  69874. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69875. if (subMaterial) {
  69876. return subMaterial.getActiveTextures();
  69877. }
  69878. else {
  69879. return [];
  69880. }
  69881. }));
  69882. var _a;
  69883. };
  69884. // Methods
  69885. MultiMaterial.prototype.getClassName = function () {
  69886. return "MultiMaterial";
  69887. };
  69888. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69889. for (var index = 0; index < this.subMaterials.length; index++) {
  69890. var subMaterial = this.subMaterials[index];
  69891. if (subMaterial) {
  69892. if (subMaterial.storeEffectOnSubMeshes) {
  69893. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69894. return false;
  69895. }
  69896. continue;
  69897. }
  69898. if (!subMaterial.isReady(mesh)) {
  69899. return false;
  69900. }
  69901. }
  69902. }
  69903. return true;
  69904. };
  69905. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69906. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69907. for (var index = 0; index < this.subMaterials.length; index++) {
  69908. var subMaterial = null;
  69909. var current = this.subMaterials[index];
  69910. if (cloneChildren && current) {
  69911. subMaterial = current.clone(name + "-" + current.name);
  69912. }
  69913. else {
  69914. subMaterial = this.subMaterials[index];
  69915. }
  69916. newMultiMaterial.subMaterials.push(subMaterial);
  69917. }
  69918. return newMultiMaterial;
  69919. };
  69920. MultiMaterial.prototype.serialize = function () {
  69921. var serializationObject = {};
  69922. serializationObject.name = this.name;
  69923. serializationObject.id = this.id;
  69924. if (BABYLON.Tags) {
  69925. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69926. }
  69927. serializationObject.materials = [];
  69928. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69929. var subMat = this.subMaterials[matIndex];
  69930. if (subMat) {
  69931. serializationObject.materials.push(subMat.id);
  69932. }
  69933. else {
  69934. serializationObject.materials.push(null);
  69935. }
  69936. }
  69937. return serializationObject;
  69938. };
  69939. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69940. var scene = this.getScene();
  69941. if (!scene) {
  69942. return;
  69943. }
  69944. var index = scene.multiMaterials.indexOf(this);
  69945. if (index >= 0) {
  69946. scene.multiMaterials.splice(index, 1);
  69947. }
  69948. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69949. };
  69950. return MultiMaterial;
  69951. }(BABYLON.Material));
  69952. BABYLON.MultiMaterial = MultiMaterial;
  69953. })(BABYLON || (BABYLON = {}));
  69954. //# sourceMappingURL=babylon.multiMaterial.js.map
  69955. var BABYLON;
  69956. (function (BABYLON) {
  69957. var FreeCameraTouchInput = /** @class */ (function () {
  69958. function FreeCameraTouchInput() {
  69959. this._offsetX = null;
  69960. this._offsetY = null;
  69961. this._pointerPressed = new Array();
  69962. this.touchAngularSensibility = 200000.0;
  69963. this.touchMoveSensibility = 250.0;
  69964. }
  69965. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69966. var _this = this;
  69967. var previousPosition = null;
  69968. if (this._pointerInput === undefined) {
  69969. this._onLostFocus = function (evt) {
  69970. _this._offsetX = null;
  69971. _this._offsetY = null;
  69972. };
  69973. this._pointerInput = function (p, s) {
  69974. var evt = p.event;
  69975. if (evt.pointerType === "mouse") {
  69976. return;
  69977. }
  69978. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69979. if (!noPreventDefault) {
  69980. evt.preventDefault();
  69981. }
  69982. _this._pointerPressed.push(evt.pointerId);
  69983. if (_this._pointerPressed.length !== 1) {
  69984. return;
  69985. }
  69986. previousPosition = {
  69987. x: evt.clientX,
  69988. y: evt.clientY
  69989. };
  69990. }
  69991. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69992. if (!noPreventDefault) {
  69993. evt.preventDefault();
  69994. }
  69995. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69996. if (index === -1) {
  69997. return;
  69998. }
  69999. _this._pointerPressed.splice(index, 1);
  70000. if (index != 0) {
  70001. return;
  70002. }
  70003. previousPosition = null;
  70004. _this._offsetX = null;
  70005. _this._offsetY = null;
  70006. }
  70007. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70008. if (!noPreventDefault) {
  70009. evt.preventDefault();
  70010. }
  70011. if (!previousPosition) {
  70012. return;
  70013. }
  70014. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70015. if (index != 0) {
  70016. return;
  70017. }
  70018. _this._offsetX = evt.clientX - previousPosition.x;
  70019. _this._offsetY = -(evt.clientY - previousPosition.y);
  70020. }
  70021. };
  70022. }
  70023. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70024. if (this._onLostFocus) {
  70025. element.addEventListener("blur", this._onLostFocus);
  70026. }
  70027. };
  70028. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70029. if (this._pointerInput && element) {
  70030. if (this._observer) {
  70031. this.camera.getScene().onPointerObservable.remove(this._observer);
  70032. this._observer = null;
  70033. }
  70034. if (this._onLostFocus) {
  70035. element.removeEventListener("blur", this._onLostFocus);
  70036. this._onLostFocus = null;
  70037. }
  70038. this._pointerPressed = [];
  70039. this._offsetX = null;
  70040. this._offsetY = null;
  70041. }
  70042. };
  70043. FreeCameraTouchInput.prototype.checkInputs = function () {
  70044. if (this._offsetX && this._offsetY) {
  70045. var camera = this.camera;
  70046. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70047. if (this._pointerPressed.length > 1) {
  70048. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70049. }
  70050. else {
  70051. var speed = camera._computeLocalCameraSpeed();
  70052. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70053. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70054. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70055. }
  70056. }
  70057. };
  70058. FreeCameraTouchInput.prototype.getClassName = function () {
  70059. return "FreeCameraTouchInput";
  70060. };
  70061. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70062. return "touch";
  70063. };
  70064. __decorate([
  70065. BABYLON.serialize()
  70066. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70067. __decorate([
  70068. BABYLON.serialize()
  70069. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70070. return FreeCameraTouchInput;
  70071. }());
  70072. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70073. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70074. })(BABYLON || (BABYLON = {}));
  70075. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70076. var BABYLON;
  70077. (function (BABYLON) {
  70078. // We're mainly based on the logic defined into the FreeCamera code
  70079. var TouchCamera = /** @class */ (function (_super) {
  70080. __extends(TouchCamera, _super);
  70081. //-- end properties for backward compatibility for inputs
  70082. function TouchCamera(name, position, scene) {
  70083. var _this = _super.call(this, name, position, scene) || this;
  70084. _this.inputs.addTouch();
  70085. _this._setupInputs();
  70086. return _this;
  70087. }
  70088. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70089. //-- Begin properties for backward compatibility for inputs
  70090. get: function () {
  70091. var touch = this.inputs.attached["touch"];
  70092. if (touch)
  70093. return touch.touchAngularSensibility;
  70094. return 0;
  70095. },
  70096. set: function (value) {
  70097. var touch = this.inputs.attached["touch"];
  70098. if (touch)
  70099. touch.touchAngularSensibility = value;
  70100. },
  70101. enumerable: true,
  70102. configurable: true
  70103. });
  70104. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70105. get: function () {
  70106. var touch = this.inputs.attached["touch"];
  70107. if (touch)
  70108. return touch.touchMoveSensibility;
  70109. return 0;
  70110. },
  70111. set: function (value) {
  70112. var touch = this.inputs.attached["touch"];
  70113. if (touch)
  70114. touch.touchMoveSensibility = value;
  70115. },
  70116. enumerable: true,
  70117. configurable: true
  70118. });
  70119. TouchCamera.prototype.getClassName = function () {
  70120. return "TouchCamera";
  70121. };
  70122. TouchCamera.prototype._setupInputs = function () {
  70123. var mouse = this.inputs.attached["mouse"];
  70124. if (mouse) {
  70125. mouse.touchEnabled = false;
  70126. }
  70127. };
  70128. return TouchCamera;
  70129. }(BABYLON.FreeCamera));
  70130. BABYLON.TouchCamera = TouchCamera;
  70131. })(BABYLON || (BABYLON = {}));
  70132. //# sourceMappingURL=babylon.touchCamera.js.map
  70133. var BABYLON;
  70134. (function (BABYLON) {
  70135. var ProceduralTexture = /** @class */ (function (_super) {
  70136. __extends(ProceduralTexture, _super);
  70137. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70138. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70139. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70140. if (isCube === void 0) { isCube = false; }
  70141. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70142. _this.isCube = isCube;
  70143. _this.isEnabled = true;
  70144. _this._currentRefreshId = -1;
  70145. _this._refreshRate = 1;
  70146. _this._vertexBuffers = {};
  70147. _this._uniforms = new Array();
  70148. _this._samplers = new Array();
  70149. _this._textures = {};
  70150. _this._floats = {};
  70151. _this._floatsArrays = {};
  70152. _this._colors3 = {};
  70153. _this._colors4 = {};
  70154. _this._vectors2 = {};
  70155. _this._vectors3 = {};
  70156. _this._matrices = {};
  70157. _this._fallbackTextureUsed = false;
  70158. scene.proceduralTextures.push(_this);
  70159. _this._engine = scene.getEngine();
  70160. _this.name = name;
  70161. _this.isRenderTarget = true;
  70162. _this._size = size;
  70163. _this._generateMipMaps = generateMipMaps;
  70164. _this.setFragment(fragment);
  70165. _this._fallbackTexture = fallbackTexture;
  70166. if (isCube) {
  70167. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70168. _this.setFloat("face", 0);
  70169. }
  70170. else {
  70171. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70172. }
  70173. // VBO
  70174. var vertices = [];
  70175. vertices.push(1, 1);
  70176. vertices.push(-1, 1);
  70177. vertices.push(-1, -1);
  70178. vertices.push(1, -1);
  70179. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70180. _this._createIndexBuffer();
  70181. return _this;
  70182. }
  70183. ProceduralTexture.prototype._createIndexBuffer = function () {
  70184. var engine = this._engine;
  70185. // Indices
  70186. var indices = [];
  70187. indices.push(0);
  70188. indices.push(1);
  70189. indices.push(2);
  70190. indices.push(0);
  70191. indices.push(2);
  70192. indices.push(3);
  70193. this._indexBuffer = engine.createIndexBuffer(indices);
  70194. };
  70195. ProceduralTexture.prototype._rebuild = function () {
  70196. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70197. if (vb) {
  70198. vb._rebuild();
  70199. }
  70200. this._createIndexBuffer();
  70201. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70202. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70203. }
  70204. };
  70205. ProceduralTexture.prototype.reset = function () {
  70206. if (this._effect === undefined) {
  70207. return;
  70208. }
  70209. var engine = this._engine;
  70210. engine._releaseEffect(this._effect);
  70211. };
  70212. ProceduralTexture.prototype.isReady = function () {
  70213. var _this = this;
  70214. var engine = this._engine;
  70215. var shaders;
  70216. if (!this._fragment) {
  70217. return false;
  70218. }
  70219. if (this._fallbackTextureUsed) {
  70220. return true;
  70221. }
  70222. if (this._fragment.fragmentElement !== undefined) {
  70223. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70224. }
  70225. else {
  70226. shaders = { vertex: "procedural", fragment: this._fragment };
  70227. }
  70228. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70229. _this.releaseInternalTexture();
  70230. if (_this._fallbackTexture) {
  70231. _this._texture = _this._fallbackTexture._texture;
  70232. if (_this._texture) {
  70233. _this._texture.incrementReferences();
  70234. }
  70235. }
  70236. _this._fallbackTextureUsed = true;
  70237. });
  70238. return this._effect.isReady();
  70239. };
  70240. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70241. this._currentRefreshId = -1;
  70242. };
  70243. ProceduralTexture.prototype.setFragment = function (fragment) {
  70244. this._fragment = fragment;
  70245. };
  70246. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70247. get: function () {
  70248. return this._refreshRate;
  70249. },
  70250. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70251. set: function (value) {
  70252. this._refreshRate = value;
  70253. this.resetRefreshCounter();
  70254. },
  70255. enumerable: true,
  70256. configurable: true
  70257. });
  70258. ProceduralTexture.prototype._shouldRender = function () {
  70259. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70260. return false;
  70261. }
  70262. if (this._fallbackTextureUsed) {
  70263. return false;
  70264. }
  70265. if (this._currentRefreshId === -1) { // At least render once
  70266. this._currentRefreshId = 1;
  70267. return true;
  70268. }
  70269. if (this.refreshRate === this._currentRefreshId) {
  70270. this._currentRefreshId = 1;
  70271. return true;
  70272. }
  70273. this._currentRefreshId++;
  70274. return false;
  70275. };
  70276. ProceduralTexture.prototype.getRenderSize = function () {
  70277. return this._size;
  70278. };
  70279. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70280. if (this._fallbackTextureUsed) {
  70281. return;
  70282. }
  70283. this.releaseInternalTexture();
  70284. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70285. // Update properties
  70286. this._size = size;
  70287. this._generateMipMaps = generateMipMaps;
  70288. };
  70289. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70290. if (this._uniforms.indexOf(uniformName) === -1) {
  70291. this._uniforms.push(uniformName);
  70292. }
  70293. };
  70294. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70295. if (this._samplers.indexOf(name) === -1) {
  70296. this._samplers.push(name);
  70297. }
  70298. this._textures[name] = texture;
  70299. return this;
  70300. };
  70301. ProceduralTexture.prototype.setFloat = function (name, value) {
  70302. this._checkUniform(name);
  70303. this._floats[name] = value;
  70304. return this;
  70305. };
  70306. ProceduralTexture.prototype.setFloats = function (name, value) {
  70307. this._checkUniform(name);
  70308. this._floatsArrays[name] = value;
  70309. return this;
  70310. };
  70311. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70312. this._checkUniform(name);
  70313. this._colors3[name] = value;
  70314. return this;
  70315. };
  70316. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70317. this._checkUniform(name);
  70318. this._colors4[name] = value;
  70319. return this;
  70320. };
  70321. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70322. this._checkUniform(name);
  70323. this._vectors2[name] = value;
  70324. return this;
  70325. };
  70326. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70327. this._checkUniform(name);
  70328. this._vectors3[name] = value;
  70329. return this;
  70330. };
  70331. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70332. this._checkUniform(name);
  70333. this._matrices[name] = value;
  70334. return this;
  70335. };
  70336. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70337. var scene = this.getScene();
  70338. if (!scene) {
  70339. return;
  70340. }
  70341. var engine = this._engine;
  70342. // Render
  70343. engine.enableEffect(this._effect);
  70344. engine.setState(false);
  70345. // Texture
  70346. for (var name in this._textures) {
  70347. this._effect.setTexture(name, this._textures[name]);
  70348. }
  70349. // Float
  70350. for (name in this._floats) {
  70351. this._effect.setFloat(name, this._floats[name]);
  70352. }
  70353. // Floats
  70354. for (name in this._floatsArrays) {
  70355. this._effect.setArray(name, this._floatsArrays[name]);
  70356. }
  70357. // Color3
  70358. for (name in this._colors3) {
  70359. this._effect.setColor3(name, this._colors3[name]);
  70360. }
  70361. // Color4
  70362. for (name in this._colors4) {
  70363. var color = this._colors4[name];
  70364. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70365. }
  70366. // Vector2
  70367. for (name in this._vectors2) {
  70368. this._effect.setVector2(name, this._vectors2[name]);
  70369. }
  70370. // Vector3
  70371. for (name in this._vectors3) {
  70372. this._effect.setVector3(name, this._vectors3[name]);
  70373. }
  70374. // Matrix
  70375. for (name in this._matrices) {
  70376. this._effect.setMatrix(name, this._matrices[name]);
  70377. }
  70378. if (!this._texture) {
  70379. return;
  70380. }
  70381. if (this.isCube) {
  70382. for (var face = 0; face < 6; face++) {
  70383. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70384. // VBOs
  70385. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70386. this._effect.setFloat("face", face);
  70387. // Clear
  70388. engine.clear(scene.clearColor, true, true, true);
  70389. // Draw order
  70390. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70391. // Mipmaps
  70392. if (face === 5) {
  70393. engine.generateMipMapsForCubemap(this._texture);
  70394. }
  70395. }
  70396. }
  70397. else {
  70398. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70399. // VBOs
  70400. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70401. // Clear
  70402. engine.clear(scene.clearColor, true, true, true);
  70403. // Draw order
  70404. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70405. }
  70406. // Unbind
  70407. engine.unBindFramebuffer(this._texture, this.isCube);
  70408. if (this.onGenerated) {
  70409. this.onGenerated();
  70410. }
  70411. };
  70412. ProceduralTexture.prototype.clone = function () {
  70413. var textureSize = this.getSize();
  70414. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70415. // Base texture
  70416. newTexture.hasAlpha = this.hasAlpha;
  70417. newTexture.level = this.level;
  70418. // RenderTarget Texture
  70419. newTexture.coordinatesMode = this.coordinatesMode;
  70420. return newTexture;
  70421. };
  70422. ProceduralTexture.prototype.dispose = function () {
  70423. var scene = this.getScene();
  70424. if (!scene) {
  70425. return;
  70426. }
  70427. var index = scene.proceduralTextures.indexOf(this);
  70428. if (index >= 0) {
  70429. scene.proceduralTextures.splice(index, 1);
  70430. }
  70431. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70432. if (vertexBuffer) {
  70433. vertexBuffer.dispose();
  70434. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70435. }
  70436. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70437. this._indexBuffer = null;
  70438. }
  70439. _super.prototype.dispose.call(this);
  70440. };
  70441. __decorate([
  70442. BABYLON.serialize()
  70443. ], ProceduralTexture.prototype, "_size", void 0);
  70444. __decorate([
  70445. BABYLON.serialize()
  70446. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70447. __decorate([
  70448. BABYLON.serialize()
  70449. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70450. __decorate([
  70451. BABYLON.serialize()
  70452. ], ProceduralTexture.prototype, "refreshRate", null);
  70453. return ProceduralTexture;
  70454. }(BABYLON.Texture));
  70455. BABYLON.ProceduralTexture = ProceduralTexture;
  70456. })(BABYLON || (BABYLON = {}));
  70457. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70458. var BABYLON;
  70459. (function (BABYLON) {
  70460. var CustomProceduralTexture = /** @class */ (function (_super) {
  70461. __extends(CustomProceduralTexture, _super);
  70462. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70463. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70464. _this._animate = true;
  70465. _this._time = 0;
  70466. _this._texturePath = texturePath;
  70467. //Try to load json
  70468. _this.loadJson(texturePath);
  70469. _this.refreshRate = 1;
  70470. return _this;
  70471. }
  70472. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70473. var _this = this;
  70474. var noConfigFile = function () {
  70475. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70476. try {
  70477. _this.setFragment(_this._texturePath);
  70478. }
  70479. catch (ex) {
  70480. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70481. }
  70482. };
  70483. var configFileUrl = jsonUrl + "/config.json";
  70484. var xhr = new XMLHttpRequest();
  70485. xhr.open("GET", configFileUrl, true);
  70486. xhr.addEventListener("load", function () {
  70487. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70488. try {
  70489. _this._config = JSON.parse(xhr.response);
  70490. _this.updateShaderUniforms();
  70491. _this.updateTextures();
  70492. _this.setFragment(_this._texturePath + "/custom");
  70493. _this._animate = _this._config.animate;
  70494. _this.refreshRate = _this._config.refreshrate;
  70495. }
  70496. catch (ex) {
  70497. noConfigFile();
  70498. }
  70499. }
  70500. else {
  70501. noConfigFile();
  70502. }
  70503. }, false);
  70504. xhr.addEventListener("error", function () {
  70505. noConfigFile();
  70506. }, false);
  70507. try {
  70508. xhr.send();
  70509. }
  70510. catch (ex) {
  70511. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70512. }
  70513. };
  70514. CustomProceduralTexture.prototype.isReady = function () {
  70515. if (!_super.prototype.isReady.call(this)) {
  70516. return false;
  70517. }
  70518. for (var name in this._textures) {
  70519. var texture = this._textures[name];
  70520. if (!texture.isReady()) {
  70521. return false;
  70522. }
  70523. }
  70524. return true;
  70525. };
  70526. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70527. var scene = this.getScene();
  70528. if (this._animate && scene) {
  70529. this._time += scene.getAnimationRatio() * 0.03;
  70530. this.updateShaderUniforms();
  70531. }
  70532. _super.prototype.render.call(this, useCameraPostProcess);
  70533. };
  70534. CustomProceduralTexture.prototype.updateTextures = function () {
  70535. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70536. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70537. }
  70538. };
  70539. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70540. if (this._config) {
  70541. for (var j = 0; j < this._config.uniforms.length; j++) {
  70542. var uniform = this._config.uniforms[j];
  70543. switch (uniform.type) {
  70544. case "float":
  70545. this.setFloat(uniform.name, uniform.value);
  70546. break;
  70547. case "color3":
  70548. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70549. break;
  70550. case "color4":
  70551. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70552. break;
  70553. case "vector2":
  70554. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70555. break;
  70556. case "vector3":
  70557. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70558. break;
  70559. }
  70560. }
  70561. }
  70562. this.setFloat("time", this._time);
  70563. };
  70564. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70565. get: function () {
  70566. return this._animate;
  70567. },
  70568. set: function (value) {
  70569. this._animate = value;
  70570. },
  70571. enumerable: true,
  70572. configurable: true
  70573. });
  70574. return CustomProceduralTexture;
  70575. }(BABYLON.ProceduralTexture));
  70576. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70577. })(BABYLON || (BABYLON = {}));
  70578. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70579. var BABYLON;
  70580. (function (BABYLON) {
  70581. var FreeCameraGamepadInput = /** @class */ (function () {
  70582. function FreeCameraGamepadInput() {
  70583. this.gamepadAngularSensibility = 200;
  70584. this.gamepadMoveSensibility = 40;
  70585. // private members
  70586. this._cameraTransform = BABYLON.Matrix.Identity();
  70587. this._deltaTransform = BABYLON.Vector3.Zero();
  70588. this._vector3 = BABYLON.Vector3.Zero();
  70589. this._vector2 = BABYLON.Vector2.Zero();
  70590. }
  70591. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70592. var _this = this;
  70593. var manager = this.camera.getScene().gamepadManager;
  70594. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70595. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70596. // prioritize XBOX gamepads.
  70597. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70598. _this.gamepad = gamepad;
  70599. }
  70600. }
  70601. });
  70602. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70603. if (_this.gamepad === gamepad) {
  70604. _this.gamepad = null;
  70605. }
  70606. });
  70607. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70608. };
  70609. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70610. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70611. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70612. this.gamepad = null;
  70613. };
  70614. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70615. if (this.gamepad && this.gamepad.leftStick) {
  70616. var camera = this.camera;
  70617. var LSValues = this.gamepad.leftStick;
  70618. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70619. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70620. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70621. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70622. var RSValues = this.gamepad.rightStick;
  70623. if (RSValues) {
  70624. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70625. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70626. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70627. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70628. }
  70629. else {
  70630. RSValues = { x: 0, y: 0 };
  70631. }
  70632. if (!camera.rotationQuaternion) {
  70633. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70634. }
  70635. else {
  70636. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70637. }
  70638. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70639. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70640. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70641. camera.cameraDirection.addInPlace(this._deltaTransform);
  70642. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70643. camera.cameraRotation.addInPlace(this._vector2);
  70644. }
  70645. };
  70646. FreeCameraGamepadInput.prototype.getClassName = function () {
  70647. return "FreeCameraGamepadInput";
  70648. };
  70649. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70650. return "gamepad";
  70651. };
  70652. __decorate([
  70653. BABYLON.serialize()
  70654. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70655. __decorate([
  70656. BABYLON.serialize()
  70657. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70658. return FreeCameraGamepadInput;
  70659. }());
  70660. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70661. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70662. })(BABYLON || (BABYLON = {}));
  70663. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70664. var BABYLON;
  70665. (function (BABYLON) {
  70666. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70667. function ArcRotateCameraGamepadInput() {
  70668. this.gamepadRotationSensibility = 80;
  70669. this.gamepadMoveSensibility = 40;
  70670. }
  70671. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70672. var _this = this;
  70673. var manager = this.camera.getScene().gamepadManager;
  70674. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70675. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70676. // prioritize XBOX gamepads.
  70677. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70678. _this.gamepad = gamepad;
  70679. }
  70680. }
  70681. });
  70682. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70683. if (_this.gamepad === gamepad) {
  70684. _this.gamepad = null;
  70685. }
  70686. });
  70687. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70688. };
  70689. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70690. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70691. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70692. this.gamepad = null;
  70693. };
  70694. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70695. if (this.gamepad) {
  70696. var camera = this.camera;
  70697. var RSValues = this.gamepad.rightStick;
  70698. if (RSValues) {
  70699. if (RSValues.x != 0) {
  70700. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70701. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70702. camera.inertialAlphaOffset += normalizedRX;
  70703. }
  70704. }
  70705. if (RSValues.y != 0) {
  70706. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70707. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70708. camera.inertialBetaOffset += normalizedRY;
  70709. }
  70710. }
  70711. }
  70712. var LSValues = this.gamepad.leftStick;
  70713. if (LSValues && LSValues.y != 0) {
  70714. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70715. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70716. this.camera.inertialRadiusOffset -= normalizedLY;
  70717. }
  70718. }
  70719. }
  70720. };
  70721. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70722. return "ArcRotateCameraGamepadInput";
  70723. };
  70724. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70725. return "gamepad";
  70726. };
  70727. __decorate([
  70728. BABYLON.serialize()
  70729. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70730. __decorate([
  70731. BABYLON.serialize()
  70732. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70733. return ArcRotateCameraGamepadInput;
  70734. }());
  70735. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70736. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70737. })(BABYLON || (BABYLON = {}));
  70738. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70739. var BABYLON;
  70740. (function (BABYLON) {
  70741. var GamepadManager = /** @class */ (function () {
  70742. function GamepadManager(_scene) {
  70743. var _this = this;
  70744. this._scene = _scene;
  70745. this._babylonGamepads = [];
  70746. this._oneGamepadConnected = false;
  70747. this._isMonitoring = false;
  70748. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70749. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70750. this._gamepadEventSupported = false;
  70751. }
  70752. else {
  70753. this._gamepadEventSupported = 'GamepadEvent' in window;
  70754. this._gamepadSupport = (navigator.getGamepads ||
  70755. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70756. }
  70757. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70758. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70759. for (var i in _this._babylonGamepads) {
  70760. var gamepad = _this._babylonGamepads[i];
  70761. if (gamepad && gamepad._isConnected) {
  70762. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70763. }
  70764. }
  70765. });
  70766. this._onGamepadConnectedEvent = function (evt) {
  70767. var gamepad = evt.gamepad;
  70768. if (gamepad.index in _this._babylonGamepads) {
  70769. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70770. return;
  70771. }
  70772. }
  70773. var newGamepad;
  70774. if (_this._babylonGamepads[gamepad.index]) {
  70775. newGamepad = _this._babylonGamepads[gamepad.index];
  70776. newGamepad.browserGamepad = gamepad;
  70777. newGamepad._isConnected = true;
  70778. }
  70779. else {
  70780. newGamepad = _this._addNewGamepad(gamepad);
  70781. }
  70782. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70783. _this._startMonitoringGamepads();
  70784. };
  70785. this._onGamepadDisconnectedEvent = function (evt) {
  70786. var gamepad = evt.gamepad;
  70787. // Remove the gamepad from the list of gamepads to monitor.
  70788. for (var i in _this._babylonGamepads) {
  70789. if (_this._babylonGamepads[i].index === gamepad.index) {
  70790. var disconnectedGamepad = _this._babylonGamepads[i];
  70791. disconnectedGamepad._isConnected = false;
  70792. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70793. break;
  70794. }
  70795. }
  70796. };
  70797. if (this._gamepadSupport) {
  70798. //first add already-connected gamepads
  70799. this._updateGamepadObjects();
  70800. if (this._babylonGamepads.length) {
  70801. this._startMonitoringGamepads();
  70802. }
  70803. // Checking if the gamepad connected event is supported (like in Firefox)
  70804. if (this._gamepadEventSupported) {
  70805. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70806. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70807. }
  70808. else {
  70809. this._startMonitoringGamepads();
  70810. }
  70811. }
  70812. }
  70813. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70814. get: function () {
  70815. return this._babylonGamepads;
  70816. },
  70817. enumerable: true,
  70818. configurable: true
  70819. });
  70820. GamepadManager.prototype.getGamepadByType = function (type) {
  70821. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70822. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70823. var gamepad = _a[_i];
  70824. if (gamepad && gamepad.type === type) {
  70825. return gamepad;
  70826. }
  70827. }
  70828. return null;
  70829. };
  70830. GamepadManager.prototype.dispose = function () {
  70831. if (this._gamepadEventSupported) {
  70832. if (this._onGamepadConnectedEvent) {
  70833. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70834. }
  70835. if (this._onGamepadDisconnectedEvent) {
  70836. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70837. }
  70838. this._onGamepadConnectedEvent = null;
  70839. this._onGamepadDisconnectedEvent = null;
  70840. }
  70841. this._babylonGamepads.forEach(function (gamepad) {
  70842. gamepad.dispose();
  70843. });
  70844. this.onGamepadConnectedObservable.clear();
  70845. this.onGamepadDisconnectedObservable.clear();
  70846. this._oneGamepadConnected = false;
  70847. this._stopMonitoringGamepads();
  70848. this._babylonGamepads = [];
  70849. };
  70850. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70851. if (!this._oneGamepadConnected) {
  70852. this._oneGamepadConnected = true;
  70853. }
  70854. var newGamepad;
  70855. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70856. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70857. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70858. }
  70859. // if pose is supported, use the (WebVR) pose enabled controller
  70860. else if (gamepad.pose) {
  70861. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70862. }
  70863. else {
  70864. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70865. }
  70866. this._babylonGamepads[newGamepad.index] = newGamepad;
  70867. return newGamepad;
  70868. };
  70869. GamepadManager.prototype._startMonitoringGamepads = function () {
  70870. if (!this._isMonitoring) {
  70871. this._isMonitoring = true;
  70872. //back-comp
  70873. if (!this._scene) {
  70874. this._checkGamepadsStatus();
  70875. }
  70876. }
  70877. };
  70878. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70879. this._isMonitoring = false;
  70880. };
  70881. GamepadManager.prototype._checkGamepadsStatus = function () {
  70882. var _this = this;
  70883. // Hack to be compatible Chrome
  70884. this._updateGamepadObjects();
  70885. for (var i in this._babylonGamepads) {
  70886. var gamepad = this._babylonGamepads[i];
  70887. if (!gamepad || !gamepad.isConnected) {
  70888. continue;
  70889. }
  70890. gamepad.update();
  70891. }
  70892. if (this._isMonitoring && !this._scene) {
  70893. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70894. }
  70895. };
  70896. // This function is called only on Chrome, which does not properly support
  70897. // connection/disconnection events and forces you to recopy again the gamepad object
  70898. GamepadManager.prototype._updateGamepadObjects = function () {
  70899. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70900. for (var i = 0; i < gamepads.length; i++) {
  70901. var gamepad = gamepads[i];
  70902. if (gamepad) {
  70903. if (!this._babylonGamepads[gamepad.index]) {
  70904. var newGamepad = this._addNewGamepad(gamepad);
  70905. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70906. }
  70907. else {
  70908. // Forced to copy again this object for Chrome for unknown reason
  70909. this._babylonGamepads[i].browserGamepad = gamepad;
  70910. if (!this._babylonGamepads[i].isConnected) {
  70911. this._babylonGamepads[i]._isConnected = true;
  70912. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70913. }
  70914. }
  70915. }
  70916. }
  70917. };
  70918. return GamepadManager;
  70919. }());
  70920. BABYLON.GamepadManager = GamepadManager;
  70921. })(BABYLON || (BABYLON = {}));
  70922. //# sourceMappingURL=babylon.gamepadManager.js.map
  70923. var BABYLON;
  70924. (function (BABYLON) {
  70925. var StickValues = /** @class */ (function () {
  70926. function StickValues(x, y) {
  70927. this.x = x;
  70928. this.y = y;
  70929. }
  70930. return StickValues;
  70931. }());
  70932. BABYLON.StickValues = StickValues;
  70933. var Gamepad = /** @class */ (function () {
  70934. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70935. if (leftStickX === void 0) { leftStickX = 0; }
  70936. if (leftStickY === void 0) { leftStickY = 1; }
  70937. if (rightStickX === void 0) { rightStickX = 2; }
  70938. if (rightStickY === void 0) { rightStickY = 3; }
  70939. this.id = id;
  70940. this.index = index;
  70941. this.browserGamepad = browserGamepad;
  70942. this._isConnected = true;
  70943. this._invertLeftStickY = false;
  70944. this.type = Gamepad.GAMEPAD;
  70945. this._leftStickAxisX = leftStickX;
  70946. this._leftStickAxisY = leftStickY;
  70947. this._rightStickAxisX = rightStickX;
  70948. this._rightStickAxisY = rightStickY;
  70949. if (this.browserGamepad.axes.length >= 2) {
  70950. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70951. }
  70952. if (this.browserGamepad.axes.length >= 4) {
  70953. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70954. }
  70955. }
  70956. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70957. get: function () {
  70958. return this._isConnected;
  70959. },
  70960. enumerable: true,
  70961. configurable: true
  70962. });
  70963. Gamepad.prototype.onleftstickchanged = function (callback) {
  70964. this._onleftstickchanged = callback;
  70965. };
  70966. Gamepad.prototype.onrightstickchanged = function (callback) {
  70967. this._onrightstickchanged = callback;
  70968. };
  70969. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70970. get: function () {
  70971. return this._leftStick;
  70972. },
  70973. set: function (newValues) {
  70974. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70975. this._onleftstickchanged(newValues);
  70976. }
  70977. this._leftStick = newValues;
  70978. },
  70979. enumerable: true,
  70980. configurable: true
  70981. });
  70982. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70983. get: function () {
  70984. return this._rightStick;
  70985. },
  70986. set: function (newValues) {
  70987. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70988. this._onrightstickchanged(newValues);
  70989. }
  70990. this._rightStick = newValues;
  70991. },
  70992. enumerable: true,
  70993. configurable: true
  70994. });
  70995. Gamepad.prototype.update = function () {
  70996. if (this._leftStick) {
  70997. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70998. if (this._invertLeftStickY) {
  70999. this.leftStick.y *= -1;
  71000. }
  71001. }
  71002. if (this._rightStick) {
  71003. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71004. }
  71005. };
  71006. Gamepad.prototype.dispose = function () {
  71007. };
  71008. Gamepad.GAMEPAD = 0;
  71009. Gamepad.GENERIC = 1;
  71010. Gamepad.XBOX = 2;
  71011. Gamepad.POSE_ENABLED = 3;
  71012. return Gamepad;
  71013. }());
  71014. BABYLON.Gamepad = Gamepad;
  71015. var GenericPad = /** @class */ (function (_super) {
  71016. __extends(GenericPad, _super);
  71017. function GenericPad(id, index, browserGamepad) {
  71018. var _this = _super.call(this, id, index, browserGamepad) || this;
  71019. _this.onButtonDownObservable = new BABYLON.Observable();
  71020. _this.onButtonUpObservable = new BABYLON.Observable();
  71021. _this.type = Gamepad.GENERIC;
  71022. _this._buttons = new Array(browserGamepad.buttons.length);
  71023. return _this;
  71024. }
  71025. GenericPad.prototype.onbuttondown = function (callback) {
  71026. this._onbuttondown = callback;
  71027. };
  71028. GenericPad.prototype.onbuttonup = function (callback) {
  71029. this._onbuttonup = callback;
  71030. };
  71031. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71032. if (newValue !== currentValue) {
  71033. if (newValue === 1) {
  71034. if (this._onbuttondown) {
  71035. this._onbuttondown(buttonIndex);
  71036. }
  71037. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71038. }
  71039. if (newValue === 0) {
  71040. if (this._onbuttonup) {
  71041. this._onbuttonup(buttonIndex);
  71042. }
  71043. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71044. }
  71045. }
  71046. return newValue;
  71047. };
  71048. GenericPad.prototype.update = function () {
  71049. _super.prototype.update.call(this);
  71050. for (var index = 0; index < this._buttons.length; index++) {
  71051. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71052. }
  71053. };
  71054. GenericPad.prototype.dispose = function () {
  71055. _super.prototype.dispose.call(this);
  71056. this.onButtonDownObservable.clear();
  71057. this.onButtonUpObservable.clear();
  71058. };
  71059. return GenericPad;
  71060. }(Gamepad));
  71061. BABYLON.GenericPad = GenericPad;
  71062. })(BABYLON || (BABYLON = {}));
  71063. //# sourceMappingURL=babylon.gamepad.js.map
  71064. var BABYLON;
  71065. (function (BABYLON) {
  71066. /**
  71067. * Defines supported buttons for XBox360 compatible gamepads
  71068. */
  71069. var Xbox360Button;
  71070. (function (Xbox360Button) {
  71071. /** A */
  71072. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71073. /** B */
  71074. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71075. /** X */
  71076. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71077. /** Y */
  71078. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71079. /** Start */
  71080. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71081. /** Back */
  71082. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71083. /** Left button */
  71084. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71085. /** Right button */
  71086. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71087. /** Left stick */
  71088. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71089. /** Right stick */
  71090. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71091. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71092. /** Defines values for XBox360 DPad */
  71093. var Xbox360Dpad;
  71094. (function (Xbox360Dpad) {
  71095. /** Up */
  71096. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71097. /** Down */
  71098. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71099. /** Left */
  71100. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71101. /** Right */
  71102. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71103. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71104. /**
  71105. * Defines a XBox360 gamepad
  71106. */
  71107. var Xbox360Pad = /** @class */ (function (_super) {
  71108. __extends(Xbox360Pad, _super);
  71109. /**
  71110. * Creates a new XBox360 gamepad object
  71111. * @param id defines the id of this gamepad
  71112. * @param index defines its index
  71113. * @param gamepad defines the internal HTML gamepad object
  71114. * @param xboxOne defines if it is a XBox One gamepad
  71115. */
  71116. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71117. if (xboxOne === void 0) { xboxOne = false; }
  71118. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71119. _this._leftTrigger = 0;
  71120. _this._rightTrigger = 0;
  71121. /** Observable raised when a button is pressed */
  71122. _this.onButtonDownObservable = new BABYLON.Observable();
  71123. /** Observable raised when a button is released */
  71124. _this.onButtonUpObservable = new BABYLON.Observable();
  71125. /** Observable raised when a pad is pressed */
  71126. _this.onPadDownObservable = new BABYLON.Observable();
  71127. /** Observable raised when a pad is released */
  71128. _this.onPadUpObservable = new BABYLON.Observable();
  71129. _this._buttonA = 0;
  71130. _this._buttonB = 0;
  71131. _this._buttonX = 0;
  71132. _this._buttonY = 0;
  71133. _this._buttonBack = 0;
  71134. _this._buttonStart = 0;
  71135. _this._buttonLB = 0;
  71136. _this._buttonRB = 0;
  71137. _this._buttonLeftStick = 0;
  71138. _this._buttonRightStick = 0;
  71139. _this._dPadUp = 0;
  71140. _this._dPadDown = 0;
  71141. _this._dPadLeft = 0;
  71142. _this._dPadRight = 0;
  71143. _this._isXboxOnePad = false;
  71144. _this.type = BABYLON.Gamepad.XBOX;
  71145. _this._isXboxOnePad = xboxOne;
  71146. return _this;
  71147. }
  71148. /**
  71149. * Defines the callback to call when left trigger is pressed
  71150. * @param callback defines the callback to use
  71151. */
  71152. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71153. this._onlefttriggerchanged = callback;
  71154. };
  71155. /**
  71156. * Defines the callback to call when right trigger is pressed
  71157. * @param callback defines the callback to use
  71158. */
  71159. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71160. this._onrighttriggerchanged = callback;
  71161. };
  71162. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71163. /**
  71164. * Gets or sets left trigger value
  71165. */
  71166. get: function () {
  71167. return this._leftTrigger;
  71168. },
  71169. set: function (newValue) {
  71170. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71171. this._onlefttriggerchanged(newValue);
  71172. }
  71173. this._leftTrigger = newValue;
  71174. },
  71175. enumerable: true,
  71176. configurable: true
  71177. });
  71178. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71179. /**
  71180. * Gets or sets right trigger value
  71181. */
  71182. get: function () {
  71183. return this._rightTrigger;
  71184. },
  71185. set: function (newValue) {
  71186. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71187. this._onrighttriggerchanged(newValue);
  71188. }
  71189. this._rightTrigger = newValue;
  71190. },
  71191. enumerable: true,
  71192. configurable: true
  71193. });
  71194. /**
  71195. * Defines the callback to call when a button is pressed
  71196. * @param callback defines the callback to use
  71197. */
  71198. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71199. this._onbuttondown = callback;
  71200. };
  71201. /**
  71202. * Defines the callback to call when a button is released
  71203. * @param callback defines the callback to use
  71204. */
  71205. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71206. this._onbuttonup = callback;
  71207. };
  71208. /**
  71209. * Defines the callback to call when a pad is pressed
  71210. * @param callback defines the callback to use
  71211. */
  71212. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71213. this._ondpaddown = callback;
  71214. };
  71215. /**
  71216. * Defines the callback to call when a pad is released
  71217. * @param callback defines the callback to use
  71218. */
  71219. Xbox360Pad.prototype.ondpadup = function (callback) {
  71220. this._ondpadup = callback;
  71221. };
  71222. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71223. if (newValue !== currentValue) {
  71224. if (newValue === 1) {
  71225. if (this._onbuttondown) {
  71226. this._onbuttondown(buttonType);
  71227. }
  71228. this.onButtonDownObservable.notifyObservers(buttonType);
  71229. }
  71230. if (newValue === 0) {
  71231. if (this._onbuttonup) {
  71232. this._onbuttonup(buttonType);
  71233. }
  71234. this.onButtonUpObservable.notifyObservers(buttonType);
  71235. }
  71236. }
  71237. return newValue;
  71238. };
  71239. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71240. if (newValue !== currentValue) {
  71241. if (newValue === 1) {
  71242. if (this._ondpaddown) {
  71243. this._ondpaddown(buttonType);
  71244. }
  71245. this.onPadDownObservable.notifyObservers(buttonType);
  71246. }
  71247. if (newValue === 0) {
  71248. if (this._ondpadup) {
  71249. this._ondpadup(buttonType);
  71250. }
  71251. this.onPadUpObservable.notifyObservers(buttonType);
  71252. }
  71253. }
  71254. return newValue;
  71255. };
  71256. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71257. /** Gets or sets value of A button */
  71258. get: function () {
  71259. return this._buttonA;
  71260. },
  71261. set: function (value) {
  71262. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71263. },
  71264. enumerable: true,
  71265. configurable: true
  71266. });
  71267. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71268. /** Gets or sets value of B button */
  71269. get: function () {
  71270. return this._buttonB;
  71271. },
  71272. set: function (value) {
  71273. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71274. },
  71275. enumerable: true,
  71276. configurable: true
  71277. });
  71278. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71279. /** Gets or sets value of X button */
  71280. get: function () {
  71281. return this._buttonX;
  71282. },
  71283. set: function (value) {
  71284. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71285. },
  71286. enumerable: true,
  71287. configurable: true
  71288. });
  71289. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71290. /** Gets or sets value of Y button */
  71291. get: function () {
  71292. return this._buttonY;
  71293. },
  71294. set: function (value) {
  71295. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71296. },
  71297. enumerable: true,
  71298. configurable: true
  71299. });
  71300. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71301. /** Gets or sets value of Start button */
  71302. get: function () {
  71303. return this._buttonStart;
  71304. },
  71305. set: function (value) {
  71306. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71307. },
  71308. enumerable: true,
  71309. configurable: true
  71310. });
  71311. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71312. /** Gets or sets value of Back button */
  71313. get: function () {
  71314. return this._buttonBack;
  71315. },
  71316. set: function (value) {
  71317. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71318. },
  71319. enumerable: true,
  71320. configurable: true
  71321. });
  71322. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71323. /** Gets or sets value of Left button */
  71324. get: function () {
  71325. return this._buttonLB;
  71326. },
  71327. set: function (value) {
  71328. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71329. },
  71330. enumerable: true,
  71331. configurable: true
  71332. });
  71333. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71334. /** Gets or sets value of Right button */
  71335. get: function () {
  71336. return this._buttonRB;
  71337. },
  71338. set: function (value) {
  71339. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71340. },
  71341. enumerable: true,
  71342. configurable: true
  71343. });
  71344. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71345. /** Gets or sets value of left stick */
  71346. get: function () {
  71347. return this._buttonLeftStick;
  71348. },
  71349. set: function (value) {
  71350. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71351. },
  71352. enumerable: true,
  71353. configurable: true
  71354. });
  71355. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71356. /** Gets or sets value of right stick */
  71357. get: function () {
  71358. return this._buttonRightStick;
  71359. },
  71360. set: function (value) {
  71361. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71362. },
  71363. enumerable: true,
  71364. configurable: true
  71365. });
  71366. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71367. /** Gets or sets value of DPad up */
  71368. get: function () {
  71369. return this._dPadUp;
  71370. },
  71371. set: function (value) {
  71372. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71373. },
  71374. enumerable: true,
  71375. configurable: true
  71376. });
  71377. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71378. /** Gets or sets value of DPad down */
  71379. get: function () {
  71380. return this._dPadDown;
  71381. },
  71382. set: function (value) {
  71383. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71384. },
  71385. enumerable: true,
  71386. configurable: true
  71387. });
  71388. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71389. /** Gets or sets value of DPad left */
  71390. get: function () {
  71391. return this._dPadLeft;
  71392. },
  71393. set: function (value) {
  71394. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71395. },
  71396. enumerable: true,
  71397. configurable: true
  71398. });
  71399. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71400. /** Gets or sets value of DPad right */
  71401. get: function () {
  71402. return this._dPadRight;
  71403. },
  71404. set: function (value) {
  71405. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71406. },
  71407. enumerable: true,
  71408. configurable: true
  71409. });
  71410. /**
  71411. * Force the gamepad to synchronize with device values
  71412. */
  71413. Xbox360Pad.prototype.update = function () {
  71414. _super.prototype.update.call(this);
  71415. if (this._isXboxOnePad) {
  71416. this.buttonA = this.browserGamepad.buttons[0].value;
  71417. this.buttonB = this.browserGamepad.buttons[1].value;
  71418. this.buttonX = this.browserGamepad.buttons[2].value;
  71419. this.buttonY = this.browserGamepad.buttons[3].value;
  71420. this.buttonLB = this.browserGamepad.buttons[4].value;
  71421. this.buttonRB = this.browserGamepad.buttons[5].value;
  71422. this.leftTrigger = this.browserGamepad.axes[2];
  71423. this.rightTrigger = this.browserGamepad.axes[5];
  71424. this.buttonBack = this.browserGamepad.buttons[9].value;
  71425. this.buttonStart = this.browserGamepad.buttons[8].value;
  71426. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71427. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71428. this.dPadUp = this.browserGamepad.buttons[11].value;
  71429. this.dPadDown = this.browserGamepad.buttons[12].value;
  71430. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71431. this.dPadRight = this.browserGamepad.buttons[14].value;
  71432. }
  71433. else {
  71434. this.buttonA = this.browserGamepad.buttons[0].value;
  71435. this.buttonB = this.browserGamepad.buttons[1].value;
  71436. this.buttonX = this.browserGamepad.buttons[2].value;
  71437. this.buttonY = this.browserGamepad.buttons[3].value;
  71438. this.buttonLB = this.browserGamepad.buttons[4].value;
  71439. this.buttonRB = this.browserGamepad.buttons[5].value;
  71440. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71441. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71442. this.buttonBack = this.browserGamepad.buttons[8].value;
  71443. this.buttonStart = this.browserGamepad.buttons[9].value;
  71444. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71445. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71446. this.dPadUp = this.browserGamepad.buttons[12].value;
  71447. this.dPadDown = this.browserGamepad.buttons[13].value;
  71448. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71449. this.dPadRight = this.browserGamepad.buttons[15].value;
  71450. }
  71451. };
  71452. Xbox360Pad.prototype.dispose = function () {
  71453. _super.prototype.dispose.call(this);
  71454. this.onButtonDownObservable.clear();
  71455. this.onButtonUpObservable.clear();
  71456. this.onPadDownObservable.clear();
  71457. this.onPadUpObservable.clear();
  71458. };
  71459. return Xbox360Pad;
  71460. }(BABYLON.Gamepad));
  71461. BABYLON.Xbox360Pad = Xbox360Pad;
  71462. })(BABYLON || (BABYLON = {}));
  71463. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71464. var BABYLON;
  71465. (function (BABYLON) {
  71466. /**
  71467. * Defines the types of pose enabled controllers that are supported
  71468. */
  71469. var PoseEnabledControllerType;
  71470. (function (PoseEnabledControllerType) {
  71471. /**
  71472. * HTC Vive
  71473. */
  71474. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71475. /**
  71476. * Oculus Rift
  71477. */
  71478. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71479. /**
  71480. * Windows mixed reality
  71481. */
  71482. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71483. /**
  71484. * Samsung gear VR
  71485. */
  71486. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71487. /**
  71488. * Google Daydream
  71489. */
  71490. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71491. /**
  71492. * Generic
  71493. */
  71494. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71495. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71496. /**
  71497. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71498. */
  71499. var PoseEnabledControllerHelper = /** @class */ (function () {
  71500. function PoseEnabledControllerHelper() {
  71501. }
  71502. /**
  71503. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71504. * @param vrGamepad the gamepad to initialized
  71505. * @returns a vr controller of the type the gamepad identified as
  71506. */
  71507. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71508. // Oculus Touch
  71509. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71510. return new BABYLON.OculusTouchController(vrGamepad);
  71511. }
  71512. // Windows Mixed Reality controllers
  71513. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71514. return new BABYLON.WindowsMotionController(vrGamepad);
  71515. }
  71516. // HTC Vive
  71517. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71518. return new BABYLON.ViveController(vrGamepad);
  71519. }
  71520. // Samsung/Oculus Gear VR or Oculus Go
  71521. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71522. return new BABYLON.GearVRController(vrGamepad);
  71523. }
  71524. // Google Daydream
  71525. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71526. return new BABYLON.DaydreamController(vrGamepad);
  71527. }
  71528. // Generic
  71529. else {
  71530. return new BABYLON.GenericController(vrGamepad);
  71531. }
  71532. };
  71533. return PoseEnabledControllerHelper;
  71534. }());
  71535. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71536. /**
  71537. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71538. */
  71539. var PoseEnabledController = /** @class */ (function (_super) {
  71540. __extends(PoseEnabledController, _super);
  71541. /**
  71542. * Creates a new PoseEnabledController from a gamepad
  71543. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71544. */
  71545. function PoseEnabledController(browserGamepad) {
  71546. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71547. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71548. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71549. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71550. /**
  71551. * The device position in babylon space
  71552. */
  71553. _this.devicePosition = BABYLON.Vector3.Zero();
  71554. /**
  71555. * The device rotation in babylon space
  71556. */
  71557. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71558. /**
  71559. * The scale factor of the device in babylon space
  71560. */
  71561. _this.deviceScaleFactor = 1;
  71562. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71563. /**
  71564. * Internal, matrix used to convert room space to babylon space
  71565. */
  71566. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71567. /**
  71568. * Node to be used when casting a ray from the controller
  71569. */
  71570. _this._pointingPoseNode = null;
  71571. _this._workingMatrix = BABYLON.Matrix.Identity();
  71572. /**
  71573. * @hidden
  71574. */
  71575. _this._meshAttachedObservable = new BABYLON.Observable();
  71576. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71577. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71578. _this.position = BABYLON.Vector3.Zero();
  71579. _this.rotationQuaternion = new BABYLON.Quaternion();
  71580. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71581. _this._calculatedRotation = new BABYLON.Quaternion();
  71582. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71583. return _this;
  71584. }
  71585. /**
  71586. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71587. */
  71588. PoseEnabledController.prototype.update = function () {
  71589. _super.prototype.update.call(this);
  71590. this._updatePoseAndMesh();
  71591. };
  71592. /**
  71593. * Updates only the pose device and mesh without doing any button event checking
  71594. */
  71595. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  71596. var pose = this.browserGamepad.pose;
  71597. this.updateFromDevice(pose);
  71598. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71599. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71600. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71601. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71602. if (this._mesh) {
  71603. this._mesh.position.copyFrom(this.devicePosition);
  71604. if (this._mesh.rotationQuaternion) {
  71605. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71606. }
  71607. }
  71608. };
  71609. /**
  71610. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71611. * @param poseData raw pose fromthe device
  71612. */
  71613. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71614. if (poseData) {
  71615. this.rawPose = poseData;
  71616. if (poseData.position) {
  71617. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71618. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71619. this._deviceRoomPosition.z *= -1;
  71620. }
  71621. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71622. this._calculatedPosition.addInPlace(this.position);
  71623. }
  71624. var pose = this.rawPose;
  71625. if (poseData.orientation && pose.orientation) {
  71626. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71627. if (this._mesh) {
  71628. if (this._mesh.getScene().useRightHandedSystem) {
  71629. this._deviceRoomRotationQuaternion.z *= -1;
  71630. this._deviceRoomRotationQuaternion.w *= -1;
  71631. }
  71632. else {
  71633. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71634. }
  71635. }
  71636. // if the camera is set, rotate to the camera's rotation
  71637. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71638. }
  71639. }
  71640. };
  71641. /**
  71642. * Attaches a mesh to the controller
  71643. * @param mesh the mesh to be attached
  71644. */
  71645. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71646. if (this._mesh) {
  71647. this._mesh.parent = null;
  71648. }
  71649. this._mesh = mesh;
  71650. if (this._poseControlledCamera) {
  71651. this._mesh.parent = this._poseControlledCamera;
  71652. }
  71653. if (!this._mesh.rotationQuaternion) {
  71654. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71655. }
  71656. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  71657. this._updatePoseAndMesh();
  71658. if (this._pointingPoseNode) {
  71659. var parents = [];
  71660. var obj = this._pointingPoseNode;
  71661. while (obj.parent) {
  71662. parents.push(obj.parent);
  71663. obj = obj.parent;
  71664. }
  71665. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71666. }
  71667. this._meshAttachedObservable.notifyObservers(mesh);
  71668. };
  71669. /**
  71670. * Attaches the controllers mesh to a camera
  71671. * @param camera the camera the mesh should be attached to
  71672. */
  71673. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71674. this._poseControlledCamera = camera;
  71675. if (this._mesh) {
  71676. this._mesh.parent = this._poseControlledCamera;
  71677. }
  71678. };
  71679. /**
  71680. * Disposes of the controller
  71681. */
  71682. PoseEnabledController.prototype.dispose = function () {
  71683. if (this._mesh) {
  71684. this._mesh.dispose();
  71685. }
  71686. this._mesh = null;
  71687. _super.prototype.dispose.call(this);
  71688. };
  71689. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71690. /**
  71691. * The mesh that is attached to the controller
  71692. */
  71693. get: function () {
  71694. return this._mesh;
  71695. },
  71696. enumerable: true,
  71697. configurable: true
  71698. });
  71699. /**
  71700. * Gets the ray of the controller in the direction the controller is pointing
  71701. * @param length the length the resulting ray should be
  71702. * @returns a ray in the direction the controller is pointing
  71703. */
  71704. PoseEnabledController.prototype.getForwardRay = function (length) {
  71705. if (length === void 0) { length = 100; }
  71706. if (!this.mesh) {
  71707. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71708. }
  71709. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71710. var origin = m.getTranslation();
  71711. var forward = new BABYLON.Vector3(0, 0, -1);
  71712. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71713. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71714. return new BABYLON.Ray(origin, direction, length);
  71715. };
  71716. /**
  71717. * Name of the child mesh that can be used to cast a ray from the controller
  71718. */
  71719. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71720. return PoseEnabledController;
  71721. }(BABYLON.Gamepad));
  71722. BABYLON.PoseEnabledController = PoseEnabledController;
  71723. })(BABYLON || (BABYLON = {}));
  71724. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71725. var BABYLON;
  71726. (function (BABYLON) {
  71727. /**
  71728. * Defines the WebVRController object that represents controllers tracked in 3D space
  71729. */
  71730. var WebVRController = /** @class */ (function (_super) {
  71731. __extends(WebVRController, _super);
  71732. /**
  71733. * Creates a new WebVRController from a gamepad
  71734. * @param vrGamepad the gamepad that the WebVRController should be created from
  71735. */
  71736. function WebVRController(vrGamepad) {
  71737. var _this = _super.call(this, vrGamepad) || this;
  71738. // Observables
  71739. /**
  71740. * Fired when the trigger state has changed
  71741. */
  71742. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71743. /**
  71744. * Fired when the main button state has changed
  71745. */
  71746. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71747. /**
  71748. * Fired when the secondary button state has changed
  71749. */
  71750. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71751. /**
  71752. * Fired when the pad state has changed
  71753. */
  71754. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71755. /**
  71756. * Fired when controllers stick values have changed
  71757. */
  71758. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71759. /**
  71760. * X and Y axis corrisponding to the controllers joystick
  71761. */
  71762. _this.pad = { x: 0, y: 0 };
  71763. // avoid GC, store state in a tmp object
  71764. _this._changes = {
  71765. pressChanged: false,
  71766. touchChanged: false,
  71767. valueChanged: false,
  71768. changed: false
  71769. };
  71770. _this._buttons = new Array(vrGamepad.buttons.length);
  71771. _this.hand = vrGamepad.hand;
  71772. return _this;
  71773. }
  71774. /**
  71775. * Fired when a controller button's state has changed
  71776. * @param callback the callback containing the button that was modified
  71777. */
  71778. WebVRController.prototype.onButtonStateChange = function (callback) {
  71779. this._onButtonStateChange = callback;
  71780. };
  71781. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71782. /**
  71783. * The default controller model for the controller
  71784. */
  71785. get: function () {
  71786. return this._defaultModel;
  71787. },
  71788. enumerable: true,
  71789. configurable: true
  71790. });
  71791. /**
  71792. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71793. */
  71794. WebVRController.prototype.update = function () {
  71795. _super.prototype.update.call(this);
  71796. for (var index = 0; index < this._buttons.length; index++) {
  71797. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71798. }
  71799. ;
  71800. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71801. this.pad.x = this.leftStick.x;
  71802. this.pad.y = this.leftStick.y;
  71803. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71804. }
  71805. };
  71806. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71807. if (!newState) {
  71808. newState = {
  71809. pressed: false,
  71810. touched: false,
  71811. value: 0
  71812. };
  71813. }
  71814. if (!currentState) {
  71815. this._buttons[buttonIndex] = {
  71816. pressed: newState.pressed,
  71817. touched: newState.touched,
  71818. value: newState.value
  71819. };
  71820. return;
  71821. }
  71822. this._checkChanges(newState, currentState);
  71823. if (this._changes.changed) {
  71824. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71825. this._handleButtonChange(buttonIndex, newState, this._changes);
  71826. }
  71827. this._buttons[buttonIndex].pressed = newState.pressed;
  71828. this._buttons[buttonIndex].touched = newState.touched;
  71829. // oculus triggers are never 0, thou not touched.
  71830. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71831. };
  71832. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71833. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71834. this._changes.touchChanged = newState.touched !== currentState.touched;
  71835. this._changes.valueChanged = newState.value !== currentState.value;
  71836. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71837. return this._changes;
  71838. };
  71839. /**
  71840. * Disposes of th webVRCOntroller
  71841. */
  71842. WebVRController.prototype.dispose = function () {
  71843. _super.prototype.dispose.call(this);
  71844. this.onTriggerStateChangedObservable.clear();
  71845. this.onMainButtonStateChangedObservable.clear();
  71846. this.onSecondaryButtonStateChangedObservable.clear();
  71847. this.onPadStateChangedObservable.clear();
  71848. this.onPadValuesChangedObservable.clear();
  71849. };
  71850. return WebVRController;
  71851. }(BABYLON.PoseEnabledController));
  71852. BABYLON.WebVRController = WebVRController;
  71853. })(BABYLON || (BABYLON = {}));
  71854. //# sourceMappingURL=babylon.webVRController.js.map
  71855. var BABYLON;
  71856. (function (BABYLON) {
  71857. /**
  71858. * Oculus Touch Controller
  71859. */
  71860. var OculusTouchController = /** @class */ (function (_super) {
  71861. __extends(OculusTouchController, _super);
  71862. /**
  71863. * Creates a new OculusTouchController from a gamepad
  71864. * @param vrGamepad the gamepad that the controller should be created from
  71865. */
  71866. function OculusTouchController(vrGamepad) {
  71867. var _this = _super.call(this, vrGamepad) || this;
  71868. /**
  71869. * Fired when the secondary trigger on this controller is modified
  71870. */
  71871. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71872. /**
  71873. * Fired when the thumb rest on this controller is modified
  71874. */
  71875. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71876. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71877. return _this;
  71878. }
  71879. /**
  71880. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71881. * @param scene scene in which to add meshes
  71882. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71883. */
  71884. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71885. var _this = this;
  71886. var meshName;
  71887. // Hand
  71888. if (this.hand === 'left') {
  71889. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71890. }
  71891. else { // Right is the default if no hand is specified
  71892. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71893. }
  71894. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71895. /*
  71896. Parent Mesh name: oculus_touch_left
  71897. - body
  71898. - trigger
  71899. - thumbstick
  71900. - grip
  71901. - button_y
  71902. - button_x
  71903. - button_enter
  71904. */
  71905. _this._defaultModel = newMeshes[1];
  71906. _this.attachToMesh(_this._defaultModel);
  71907. if (meshLoaded) {
  71908. meshLoaded(_this._defaultModel);
  71909. }
  71910. });
  71911. };
  71912. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71913. /**
  71914. * Fired when the A button on this controller is modified
  71915. */
  71916. get: function () {
  71917. if (this.hand === 'right') {
  71918. return this.onMainButtonStateChangedObservable;
  71919. }
  71920. else {
  71921. throw new Error('No A button on left hand');
  71922. }
  71923. },
  71924. enumerable: true,
  71925. configurable: true
  71926. });
  71927. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71928. /**
  71929. * Fired when the B button on this controller is modified
  71930. */
  71931. get: function () {
  71932. if (this.hand === 'right') {
  71933. return this.onSecondaryButtonStateChangedObservable;
  71934. }
  71935. else {
  71936. throw new Error('No B button on left hand');
  71937. }
  71938. },
  71939. enumerable: true,
  71940. configurable: true
  71941. });
  71942. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71943. /**
  71944. * Fired when the X button on this controller is modified
  71945. */
  71946. get: function () {
  71947. if (this.hand === 'left') {
  71948. return this.onMainButtonStateChangedObservable;
  71949. }
  71950. else {
  71951. throw new Error('No X button on right hand');
  71952. }
  71953. },
  71954. enumerable: true,
  71955. configurable: true
  71956. });
  71957. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71958. /**
  71959. * Fired when the Y button on this controller is modified
  71960. */
  71961. get: function () {
  71962. if (this.hand === 'left') {
  71963. return this.onSecondaryButtonStateChangedObservable;
  71964. }
  71965. else {
  71966. throw new Error('No Y button on right hand');
  71967. }
  71968. },
  71969. enumerable: true,
  71970. configurable: true
  71971. });
  71972. /**
  71973. * Called once for each button that changed state since the last frame
  71974. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71975. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71976. * 2) secondary trigger (same)
  71977. * 3) A (right) X (left), touch, pressed = value
  71978. * 4) B / Y
  71979. * 5) thumb rest
  71980. * @param buttonIdx Which button index changed
  71981. * @param state New state of the button
  71982. * @param changes Which properties on the state changed since last frame
  71983. */
  71984. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71985. var notifyObject = state; //{ state: state, changes: changes };
  71986. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71987. switch (buttonIdx) {
  71988. case 0:
  71989. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71990. return;
  71991. case 1: // index trigger
  71992. if (this._defaultModel) {
  71993. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71994. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71995. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71996. }
  71997. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71998. return;
  71999. case 2: // secondary trigger
  72000. if (this._defaultModel) {
  72001. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72002. }
  72003. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72004. return;
  72005. case 3:
  72006. if (this._defaultModel) {
  72007. if (notifyObject.pressed) {
  72008. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72009. }
  72010. else {
  72011. (this._defaultModel.getChildren()[1]).position.y = 0;
  72012. }
  72013. }
  72014. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72015. return;
  72016. case 4:
  72017. if (this._defaultModel) {
  72018. if (notifyObject.pressed) {
  72019. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72020. }
  72021. else {
  72022. (this._defaultModel.getChildren()[2]).position.y = 0;
  72023. }
  72024. }
  72025. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72026. return;
  72027. case 5:
  72028. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72029. return;
  72030. }
  72031. };
  72032. /**
  72033. * Base Url for the controller model.
  72034. */
  72035. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72036. /**
  72037. * File name for the left controller model.
  72038. */
  72039. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72040. /**
  72041. * File name for the right controller model.
  72042. */
  72043. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72044. return OculusTouchController;
  72045. }(BABYLON.WebVRController));
  72046. BABYLON.OculusTouchController = OculusTouchController;
  72047. })(BABYLON || (BABYLON = {}));
  72048. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72049. var BABYLON;
  72050. (function (BABYLON) {
  72051. /**
  72052. * Vive Controller
  72053. */
  72054. var ViveController = /** @class */ (function (_super) {
  72055. __extends(ViveController, _super);
  72056. /**
  72057. * Creates a new ViveController from a gamepad
  72058. * @param vrGamepad the gamepad that the controller should be created from
  72059. */
  72060. function ViveController(vrGamepad) {
  72061. var _this = _super.call(this, vrGamepad) || this;
  72062. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72063. _this._invertLeftStickY = true;
  72064. return _this;
  72065. }
  72066. /**
  72067. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72068. * @param scene scene in which to add meshes
  72069. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72070. */
  72071. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72072. var _this = this;
  72073. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72074. /*
  72075. Parent Mesh name: ViveWand
  72076. - body
  72077. - r_gripper
  72078. - l_gripper
  72079. - menu_button
  72080. - system_button
  72081. - trackpad
  72082. - trigger
  72083. - LED
  72084. */
  72085. _this._defaultModel = newMeshes[1];
  72086. _this.attachToMesh(_this._defaultModel);
  72087. if (meshLoaded) {
  72088. meshLoaded(_this._defaultModel);
  72089. }
  72090. });
  72091. };
  72092. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72093. /**
  72094. * Fired when the left button on this controller is modified
  72095. */
  72096. get: function () {
  72097. return this.onMainButtonStateChangedObservable;
  72098. },
  72099. enumerable: true,
  72100. configurable: true
  72101. });
  72102. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72103. /**
  72104. * Fired when the right button on this controller is modified
  72105. */
  72106. get: function () {
  72107. return this.onMainButtonStateChangedObservable;
  72108. },
  72109. enumerable: true,
  72110. configurable: true
  72111. });
  72112. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72113. /**
  72114. * Fired when the menu button on this controller is modified
  72115. */
  72116. get: function () {
  72117. return this.onSecondaryButtonStateChangedObservable;
  72118. },
  72119. enumerable: true,
  72120. configurable: true
  72121. });
  72122. /**
  72123. * Called once for each button that changed state since the last frame
  72124. * Vive mapping:
  72125. * 0: touchpad
  72126. * 1: trigger
  72127. * 2: left AND right buttons
  72128. * 3: menu button
  72129. * @param buttonIdx Which button index changed
  72130. * @param state New state of the button
  72131. * @param changes Which properties on the state changed since last frame
  72132. */
  72133. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72134. var notifyObject = state; //{ state: state, changes: changes };
  72135. switch (buttonIdx) {
  72136. case 0:
  72137. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72138. return;
  72139. case 1: // index trigger
  72140. if (this._defaultModel) {
  72141. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72142. }
  72143. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72144. return;
  72145. case 2: // left AND right button
  72146. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72147. return;
  72148. case 3:
  72149. if (this._defaultModel) {
  72150. if (notifyObject.pressed) {
  72151. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72152. }
  72153. else {
  72154. (this._defaultModel.getChildren()[2]).position.y = 0;
  72155. }
  72156. }
  72157. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72158. return;
  72159. }
  72160. };
  72161. /**
  72162. * Base Url for the controller model.
  72163. */
  72164. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72165. /**
  72166. * File name for the controller model.
  72167. */
  72168. ViveController.MODEL_FILENAME = 'wand.babylon';
  72169. return ViveController;
  72170. }(BABYLON.WebVRController));
  72171. BABYLON.ViveController = ViveController;
  72172. })(BABYLON || (BABYLON = {}));
  72173. //# sourceMappingURL=babylon.viveController.js.map
  72174. var BABYLON;
  72175. (function (BABYLON) {
  72176. /**
  72177. * Generic Controller
  72178. */
  72179. var GenericController = /** @class */ (function (_super) {
  72180. __extends(GenericController, _super);
  72181. /**
  72182. * Creates a new GenericController from a gamepad
  72183. * @param vrGamepad the gamepad that the controller should be created from
  72184. */
  72185. function GenericController(vrGamepad) {
  72186. return _super.call(this, vrGamepad) || this;
  72187. }
  72188. /**
  72189. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72190. * @param scene scene in which to add meshes
  72191. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72192. */
  72193. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72194. var _this = this;
  72195. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72196. _this._defaultModel = newMeshes[1];
  72197. _this.attachToMesh(_this._defaultModel);
  72198. if (meshLoaded) {
  72199. meshLoaded(_this._defaultModel);
  72200. }
  72201. });
  72202. };
  72203. /**
  72204. * Called once for each button that changed state since the last frame
  72205. * @param buttonIdx Which button index changed
  72206. * @param state New state of the button
  72207. * @param changes Which properties on the state changed since last frame
  72208. */
  72209. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72210. console.log("Button id: " + buttonIdx + "state: ");
  72211. console.dir(state);
  72212. };
  72213. /**
  72214. * Base Url for the controller model.
  72215. */
  72216. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72217. /**
  72218. * File name for the controller model.
  72219. */
  72220. GenericController.MODEL_FILENAME = 'generic.babylon';
  72221. return GenericController;
  72222. }(BABYLON.WebVRController));
  72223. BABYLON.GenericController = GenericController;
  72224. })(BABYLON || (BABYLON = {}));
  72225. //# sourceMappingURL=babylon.genericController.js.map
  72226. var BABYLON;
  72227. (function (BABYLON) {
  72228. /**
  72229. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72230. */
  72231. var LoadedMeshInfo = /** @class */ (function () {
  72232. function LoadedMeshInfo() {
  72233. /**
  72234. * Map of the button meshes contained in the controller
  72235. */
  72236. this.buttonMeshes = {};
  72237. /**
  72238. * Map of the axis meshes contained in the controller
  72239. */
  72240. this.axisMeshes = {};
  72241. }
  72242. return LoadedMeshInfo;
  72243. }());
  72244. /**
  72245. * Defines the WindowsMotionController object that the state of the windows motion controller
  72246. */
  72247. var WindowsMotionController = /** @class */ (function (_super) {
  72248. __extends(WindowsMotionController, _super);
  72249. /**
  72250. * Creates a new WindowsMotionController from a gamepad
  72251. * @param vrGamepad the gamepad that the controller should be created from
  72252. */
  72253. function WindowsMotionController(vrGamepad) {
  72254. var _this = _super.call(this, vrGamepad) || this;
  72255. _this._mapping = {
  72256. // Semantic button names
  72257. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72258. // A mapping of the button name to glTF model node name
  72259. // that should be transformed by button value.
  72260. buttonMeshNames: {
  72261. 'trigger': 'SELECT',
  72262. 'menu': 'MENU',
  72263. 'grip': 'GRASP',
  72264. 'thumbstick': 'THUMBSTICK_PRESS',
  72265. 'trackpad': 'TOUCHPAD_PRESS'
  72266. },
  72267. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72268. buttonObservableNames: {
  72269. 'trigger': 'onTriggerStateChangedObservable',
  72270. 'menu': 'onSecondaryButtonStateChangedObservable',
  72271. 'grip': 'onMainButtonStateChangedObservable',
  72272. 'thumbstick': 'onPadStateChangedObservable',
  72273. 'trackpad': 'onTrackpadChangedObservable'
  72274. },
  72275. // A mapping of the axis name to glTF model node name
  72276. // that should be transformed by axis value.
  72277. // This array mirrors the browserGamepad.axes array, such that
  72278. // the mesh corresponding to axis 0 is in this array index 0.
  72279. axisMeshNames: [
  72280. 'THUMBSTICK_X',
  72281. 'THUMBSTICK_Y',
  72282. 'TOUCHPAD_TOUCH_X',
  72283. 'TOUCHPAD_TOUCH_Y'
  72284. ],
  72285. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72286. };
  72287. /**
  72288. * Fired when the trackpad on this controller is clicked
  72289. */
  72290. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72291. /**
  72292. * Fired when the trackpad on this controller is modified
  72293. */
  72294. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72295. /**
  72296. * The current x and y values of this controller's trackpad
  72297. */
  72298. _this.trackpad = { x: 0, y: 0 };
  72299. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72300. _this._loadedMeshInfo = null;
  72301. return _this;
  72302. }
  72303. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72304. /**
  72305. * Fired when the trigger on this controller is modified
  72306. */
  72307. get: function () {
  72308. return this.onTriggerStateChangedObservable;
  72309. },
  72310. enumerable: true,
  72311. configurable: true
  72312. });
  72313. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72314. /**
  72315. * Fired when the menu button on this controller is modified
  72316. */
  72317. get: function () {
  72318. return this.onSecondaryButtonStateChangedObservable;
  72319. },
  72320. enumerable: true,
  72321. configurable: true
  72322. });
  72323. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72324. /**
  72325. * Fired when the grip button on this controller is modified
  72326. */
  72327. get: function () {
  72328. return this.onMainButtonStateChangedObservable;
  72329. },
  72330. enumerable: true,
  72331. configurable: true
  72332. });
  72333. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72334. /**
  72335. * Fired when the thumbstick button on this controller is modified
  72336. */
  72337. get: function () {
  72338. return this.onPadStateChangedObservable;
  72339. },
  72340. enumerable: true,
  72341. configurable: true
  72342. });
  72343. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72344. /**
  72345. * Fired when the touchpad button on this controller is modified
  72346. */
  72347. get: function () {
  72348. return this.onTrackpadChangedObservable;
  72349. },
  72350. enumerable: true,
  72351. configurable: true
  72352. });
  72353. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72354. /**
  72355. * Fired when the touchpad values on this controller are modified
  72356. */
  72357. get: function () {
  72358. return this.onTrackpadValuesChangedObservable;
  72359. },
  72360. enumerable: true,
  72361. configurable: true
  72362. });
  72363. WindowsMotionController.prototype._updateTrackpad = function () {
  72364. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72365. this.trackpad.x = this.browserGamepad["axes"][2];
  72366. this.trackpad.y = this.browserGamepad["axes"][3];
  72367. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72368. }
  72369. };
  72370. /**
  72371. * Called once per frame by the engine.
  72372. */
  72373. WindowsMotionController.prototype.update = function () {
  72374. _super.prototype.update.call(this);
  72375. if (this.browserGamepad.axes) {
  72376. this._updateTrackpad();
  72377. // Only need to animate axes if there is a loaded mesh
  72378. if (this._loadedMeshInfo) {
  72379. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72380. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72381. }
  72382. }
  72383. }
  72384. };
  72385. /**
  72386. * Called once for each button that changed state since the last frame
  72387. * @param buttonIdx Which button index changed
  72388. * @param state New state of the button
  72389. * @param changes Which properties on the state changed since last frame
  72390. */
  72391. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72392. var buttonName = this._mapping.buttons[buttonIdx];
  72393. if (!buttonName) {
  72394. return;
  72395. }
  72396. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72397. this._updateTrackpad();
  72398. // Only emit events for buttons that we know how to map from index to name
  72399. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72400. if (observable) {
  72401. observable.notifyObservers(state);
  72402. }
  72403. this._lerpButtonTransform(buttonName, state.value);
  72404. };
  72405. /**
  72406. * Moves the buttons on the controller mesh based on their current state
  72407. * @param buttonName the name of the button to move
  72408. * @param buttonValue the value of the button which determines the buttons new position
  72409. */
  72410. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72411. // If there is no loaded mesh, there is nothing to transform.
  72412. if (!this._loadedMeshInfo) {
  72413. return;
  72414. }
  72415. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72416. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72417. return;
  72418. }
  72419. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72420. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72421. };
  72422. /**
  72423. * Moves the axis on the controller mesh based on its current state
  72424. * @param axis the index of the axis
  72425. * @param axisValue the value of the axis which determines the meshes new position
  72426. * @hidden
  72427. */
  72428. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72429. if (!this._loadedMeshInfo) {
  72430. return;
  72431. }
  72432. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72433. if (!meshInfo) {
  72434. return;
  72435. }
  72436. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72437. return;
  72438. }
  72439. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72440. var lerpValue = axisValue * 0.5 + 0.5;
  72441. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72442. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72443. };
  72444. /**
  72445. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72446. * @param scene scene in which to add meshes
  72447. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72448. */
  72449. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72450. var _this = this;
  72451. if (forceDefault === void 0) { forceDefault = false; }
  72452. var path;
  72453. var filename;
  72454. // Checking if GLB loader is present
  72455. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72456. // Determine the device specific folder based on the ID suffix
  72457. var device = 'default';
  72458. if (this.id && !forceDefault) {
  72459. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72460. device = ((match && match[0]) || device);
  72461. }
  72462. // Hand
  72463. if (this.hand === 'left') {
  72464. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72465. }
  72466. else { // Right is the default if no hand is specified
  72467. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72468. }
  72469. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72470. }
  72471. else {
  72472. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72473. path = BABYLON.GenericController.MODEL_BASE_URL;
  72474. filename = BABYLON.GenericController.MODEL_FILENAME;
  72475. }
  72476. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72477. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72478. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72479. if (!_this._loadedMeshInfo) {
  72480. return;
  72481. }
  72482. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72483. _this.attachToMesh(_this._defaultModel);
  72484. if (meshLoaded) {
  72485. meshLoaded(_this._defaultModel);
  72486. }
  72487. }, null, function (scene, message) {
  72488. BABYLON.Tools.Log(message);
  72489. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72490. if (!forceDefault) {
  72491. _this.initControllerMesh(scene, meshLoaded, true);
  72492. }
  72493. });
  72494. };
  72495. /**
  72496. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72497. * can be transformed by button presses and axes values, based on this._mapping.
  72498. *
  72499. * @param scene scene in which the meshes exist
  72500. * @param meshes list of meshes that make up the controller model to process
  72501. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72502. */
  72503. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72504. var loadedMeshInfo = null;
  72505. // Create a new mesh to contain the glTF hierarchy
  72506. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72507. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72508. var childMesh = null;
  72509. for (var i = 0; i < meshes.length; i++) {
  72510. var mesh = meshes[i];
  72511. if (!mesh.parent) {
  72512. // Exclude controller meshes from picking results
  72513. mesh.isPickable = false;
  72514. // Handle root node, attach to the new parentMesh
  72515. childMesh = mesh;
  72516. break;
  72517. }
  72518. }
  72519. if (childMesh) {
  72520. childMesh.setParent(parentMesh);
  72521. // Create our mesh info. Note that this method will always return non-null.
  72522. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72523. }
  72524. else {
  72525. BABYLON.Tools.Warn('Could not find root node in model file.');
  72526. }
  72527. return loadedMeshInfo;
  72528. };
  72529. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72530. var loadedMeshInfo = new LoadedMeshInfo();
  72531. var i;
  72532. loadedMeshInfo.rootNode = rootNode;
  72533. // Reset the caches
  72534. loadedMeshInfo.buttonMeshes = {};
  72535. loadedMeshInfo.axisMeshes = {};
  72536. // Button Meshes
  72537. for (i = 0; i < this._mapping.buttons.length; i++) {
  72538. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72539. if (!buttonMeshName) {
  72540. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72541. continue;
  72542. }
  72543. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72544. if (!buttonMesh) {
  72545. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72546. continue;
  72547. }
  72548. var buttonMeshInfo = {
  72549. index: i,
  72550. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72551. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72552. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72553. };
  72554. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72555. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72556. }
  72557. else {
  72558. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72559. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72560. '(VALUE: ' + !!buttonMeshInfo.value +
  72561. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72562. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72563. ')');
  72564. }
  72565. }
  72566. // Axis Meshes
  72567. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72568. var axisMeshName = this._mapping.axisMeshNames[i];
  72569. if (!axisMeshName) {
  72570. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72571. continue;
  72572. }
  72573. var axisMesh = getChildByName(rootNode, axisMeshName);
  72574. if (!axisMesh) {
  72575. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72576. continue;
  72577. }
  72578. var axisMeshInfo = {
  72579. index: i,
  72580. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72581. min: getImmediateChildByName(axisMesh, 'MIN'),
  72582. max: getImmediateChildByName(axisMesh, 'MAX')
  72583. };
  72584. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72585. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72586. }
  72587. else {
  72588. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72589. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72590. '(VALUE: ' + !!axisMeshInfo.value +
  72591. ', MIN: ' + !!axisMeshInfo.min +
  72592. ', MAX:' + !!axisMeshInfo.max +
  72593. ')');
  72594. }
  72595. }
  72596. // Pointing Ray
  72597. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72598. if (!loadedMeshInfo.pointingPoseNode) {
  72599. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72600. }
  72601. else {
  72602. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72603. }
  72604. return loadedMeshInfo;
  72605. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72606. function getChildByName(node, name) {
  72607. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72608. }
  72609. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72610. function getImmediateChildByName(node, name) {
  72611. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72612. }
  72613. };
  72614. /**
  72615. * Gets the ray of the controller in the direction the controller is pointing
  72616. * @param length the length the resulting ray should be
  72617. * @returns a ray in the direction the controller is pointing
  72618. */
  72619. WindowsMotionController.prototype.getForwardRay = function (length) {
  72620. if (length === void 0) { length = 100; }
  72621. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72622. return _super.prototype.getForwardRay.call(this, length);
  72623. }
  72624. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72625. var origin = m.getTranslation();
  72626. var forward = new BABYLON.Vector3(0, 0, -1);
  72627. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72628. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72629. return new BABYLON.Ray(origin, direction, length);
  72630. };
  72631. /**
  72632. * Disposes of the controller
  72633. */
  72634. WindowsMotionController.prototype.dispose = function () {
  72635. _super.prototype.dispose.call(this);
  72636. this.onTrackpadChangedObservable.clear();
  72637. };
  72638. /**
  72639. * The base url used to load the left and right controller models
  72640. */
  72641. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72642. /**
  72643. * The name of the left controller model file
  72644. */
  72645. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72646. /**
  72647. * The name of the right controller model file
  72648. */
  72649. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72650. /**
  72651. * The controller name prefix for this controller type
  72652. */
  72653. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72654. /**
  72655. * The controller id pattern for this controller type
  72656. */
  72657. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72658. return WindowsMotionController;
  72659. }(BABYLON.WebVRController));
  72660. BABYLON.WindowsMotionController = WindowsMotionController;
  72661. })(BABYLON || (BABYLON = {}));
  72662. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72663. var BABYLON;
  72664. (function (BABYLON) {
  72665. /**
  72666. * Gear VR Controller
  72667. */
  72668. var GearVRController = /** @class */ (function (_super) {
  72669. __extends(GearVRController, _super);
  72670. /**
  72671. * Creates a new GearVRController from a gamepad
  72672. * @param vrGamepad the gamepad that the controller should be created from
  72673. */
  72674. function GearVRController(vrGamepad) {
  72675. var _this = _super.call(this, vrGamepad) || this;
  72676. _this._buttonIndexToObservableNameMap = [
  72677. 'onTrackpadChangedObservable',
  72678. 'onTriggerStateChangedObservable' // Trigger
  72679. ];
  72680. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72681. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72682. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72683. return _this;
  72684. }
  72685. /**
  72686. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72687. * @param scene scene in which to add meshes
  72688. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72689. */
  72690. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72691. var _this = this;
  72692. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72693. _this._defaultModel = newMeshes[1];
  72694. _this.attachToMesh(_this._defaultModel);
  72695. if (meshLoaded) {
  72696. meshLoaded(_this._defaultModel);
  72697. }
  72698. });
  72699. };
  72700. /**
  72701. * Called once for each button that changed state since the last frame
  72702. * @param buttonIdx Which button index changed
  72703. * @param state New state of the button
  72704. * @param changes Which properties on the state changed since last frame
  72705. */
  72706. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72707. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72708. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72709. // Only emit events for buttons that we know how to map from index to observable
  72710. var observable = this[observableName];
  72711. if (observable) {
  72712. observable.notifyObservers(state);
  72713. }
  72714. }
  72715. };
  72716. /**
  72717. * Base Url for the controller model.
  72718. */
  72719. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72720. /**
  72721. * File name for the controller model.
  72722. */
  72723. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72724. /**
  72725. * Gamepad Id prefix used to identify this controller.
  72726. */
  72727. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72728. return GearVRController;
  72729. }(BABYLON.WebVRController));
  72730. BABYLON.GearVRController = GearVRController;
  72731. })(BABYLON || (BABYLON = {}));
  72732. //# sourceMappingURL=babylon.gearVRController.js.map
  72733. var BABYLON;
  72734. (function (BABYLON) {
  72735. /**
  72736. * Google Daydream controller
  72737. */
  72738. var DaydreamController = /** @class */ (function (_super) {
  72739. __extends(DaydreamController, _super);
  72740. /**
  72741. * Creates a new DaydreamController from a gamepad
  72742. * @param vrGamepad the gamepad that the controller should be created from
  72743. */
  72744. function DaydreamController(vrGamepad) {
  72745. var _this = _super.call(this, vrGamepad) || this;
  72746. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72747. return _this;
  72748. }
  72749. /**
  72750. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72751. * @param scene scene in which to add meshes
  72752. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72753. */
  72754. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72755. var _this = this;
  72756. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72757. _this._defaultModel = newMeshes[1];
  72758. _this.attachToMesh(_this._defaultModel);
  72759. if (meshLoaded) {
  72760. meshLoaded(_this._defaultModel);
  72761. }
  72762. });
  72763. };
  72764. /**
  72765. * Called once for each button that changed state since the last frame
  72766. * @param buttonIdx Which button index changed
  72767. * @param state New state of the button
  72768. * @param changes Which properties on the state changed since last frame
  72769. */
  72770. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72771. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72772. if (buttonIdx === 0) {
  72773. var observable = this.onTriggerStateChangedObservable;
  72774. if (observable) {
  72775. observable.notifyObservers(state);
  72776. }
  72777. }
  72778. else {
  72779. // If the app or home buttons are ever made available
  72780. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72781. }
  72782. };
  72783. /**
  72784. * Base Url for the controller model.
  72785. */
  72786. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72787. /**
  72788. * File name for the controller model.
  72789. */
  72790. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72791. /**
  72792. * Gamepad Id prefix used to identify Daydream Controller.
  72793. */
  72794. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72795. return DaydreamController;
  72796. }(BABYLON.WebVRController));
  72797. BABYLON.DaydreamController = DaydreamController;
  72798. })(BABYLON || (BABYLON = {}));
  72799. //# sourceMappingURL=babylon.daydreamController.js.map
  72800. var BABYLON;
  72801. (function (BABYLON) {
  72802. var FollowCamera = /** @class */ (function (_super) {
  72803. __extends(FollowCamera, _super);
  72804. function FollowCamera(name, position, scene, lockedTarget) {
  72805. if (lockedTarget === void 0) { lockedTarget = null; }
  72806. var _this = _super.call(this, name, position, scene) || this;
  72807. _this.radius = 12;
  72808. _this.rotationOffset = 0;
  72809. _this.heightOffset = 4;
  72810. _this.cameraAcceleration = 0.05;
  72811. _this.maxCameraSpeed = 20;
  72812. _this.lockedTarget = lockedTarget;
  72813. return _this;
  72814. }
  72815. FollowCamera.prototype.getRadians = function (degrees) {
  72816. return degrees * Math.PI / 180;
  72817. };
  72818. FollowCamera.prototype.follow = function (cameraTarget) {
  72819. if (!cameraTarget)
  72820. return;
  72821. var yRotation;
  72822. if (cameraTarget.rotationQuaternion) {
  72823. var rotMatrix = new BABYLON.Matrix();
  72824. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72825. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72826. }
  72827. else {
  72828. yRotation = cameraTarget.rotation.y;
  72829. }
  72830. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72831. var targetPosition = cameraTarget.getAbsolutePosition();
  72832. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72833. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72834. var dx = targetX - this.position.x;
  72835. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72836. var dz = (targetZ) - this.position.z;
  72837. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72838. var vy = dy * this.cameraAcceleration;
  72839. var vz = dz * this.cameraAcceleration * 2;
  72840. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72841. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72842. }
  72843. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72844. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72845. }
  72846. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72847. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72848. }
  72849. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72850. this.setTarget(targetPosition);
  72851. };
  72852. FollowCamera.prototype._checkInputs = function () {
  72853. _super.prototype._checkInputs.call(this);
  72854. if (this.lockedTarget) {
  72855. this.follow(this.lockedTarget);
  72856. }
  72857. };
  72858. FollowCamera.prototype.getClassName = function () {
  72859. return "FollowCamera";
  72860. };
  72861. __decorate([
  72862. BABYLON.serialize()
  72863. ], FollowCamera.prototype, "radius", void 0);
  72864. __decorate([
  72865. BABYLON.serialize()
  72866. ], FollowCamera.prototype, "rotationOffset", void 0);
  72867. __decorate([
  72868. BABYLON.serialize()
  72869. ], FollowCamera.prototype, "heightOffset", void 0);
  72870. __decorate([
  72871. BABYLON.serialize()
  72872. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72873. __decorate([
  72874. BABYLON.serialize()
  72875. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72876. __decorate([
  72877. BABYLON.serializeAsMeshReference("lockedTargetId")
  72878. ], FollowCamera.prototype, "lockedTarget", void 0);
  72879. return FollowCamera;
  72880. }(BABYLON.TargetCamera));
  72881. BABYLON.FollowCamera = FollowCamera;
  72882. var ArcFollowCamera = /** @class */ (function (_super) {
  72883. __extends(ArcFollowCamera, _super);
  72884. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72885. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72886. _this.alpha = alpha;
  72887. _this.beta = beta;
  72888. _this.radius = radius;
  72889. _this.target = target;
  72890. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72891. _this.follow();
  72892. return _this;
  72893. }
  72894. ArcFollowCamera.prototype.follow = function () {
  72895. if (!this.target) {
  72896. return;
  72897. }
  72898. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72899. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72900. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72901. var targetPosition = this.target.getAbsolutePosition();
  72902. this.position = targetPosition.add(this._cartesianCoordinates);
  72903. this.setTarget(targetPosition);
  72904. };
  72905. ArcFollowCamera.prototype._checkInputs = function () {
  72906. _super.prototype._checkInputs.call(this);
  72907. this.follow();
  72908. };
  72909. ArcFollowCamera.prototype.getClassName = function () {
  72910. return "ArcFollowCamera";
  72911. };
  72912. return ArcFollowCamera;
  72913. }(BABYLON.TargetCamera));
  72914. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72915. })(BABYLON || (BABYLON = {}));
  72916. //# sourceMappingURL=babylon.followCamera.js.map
  72917. var BABYLON;
  72918. (function (BABYLON) {
  72919. // We're mainly based on the logic defined into the FreeCamera code
  72920. var UniversalCamera = /** @class */ (function (_super) {
  72921. __extends(UniversalCamera, _super);
  72922. //-- end properties for backward compatibility for inputs
  72923. function UniversalCamera(name, position, scene) {
  72924. var _this = _super.call(this, name, position, scene) || this;
  72925. _this.inputs.addGamepad();
  72926. return _this;
  72927. }
  72928. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72929. //-- Begin properties for backward compatibility for inputs
  72930. get: function () {
  72931. var gamepad = this.inputs.attached["gamepad"];
  72932. if (gamepad)
  72933. return gamepad.gamepadAngularSensibility;
  72934. return 0;
  72935. },
  72936. set: function (value) {
  72937. var gamepad = this.inputs.attached["gamepad"];
  72938. if (gamepad)
  72939. gamepad.gamepadAngularSensibility = value;
  72940. },
  72941. enumerable: true,
  72942. configurable: true
  72943. });
  72944. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72945. get: function () {
  72946. var gamepad = this.inputs.attached["gamepad"];
  72947. if (gamepad)
  72948. return gamepad.gamepadMoveSensibility;
  72949. return 0;
  72950. },
  72951. set: function (value) {
  72952. var gamepad = this.inputs.attached["gamepad"];
  72953. if (gamepad)
  72954. gamepad.gamepadMoveSensibility = value;
  72955. },
  72956. enumerable: true,
  72957. configurable: true
  72958. });
  72959. UniversalCamera.prototype.getClassName = function () {
  72960. return "UniversalCamera";
  72961. };
  72962. return UniversalCamera;
  72963. }(BABYLON.TouchCamera));
  72964. BABYLON.UniversalCamera = UniversalCamera;
  72965. })(BABYLON || (BABYLON = {}));
  72966. //# sourceMappingURL=babylon.universalCamera.js.map
  72967. var BABYLON;
  72968. (function (BABYLON) {
  72969. // We're mainly based on the logic defined into the FreeCamera code
  72970. var GamepadCamera = /** @class */ (function (_super) {
  72971. __extends(GamepadCamera, _super);
  72972. //-- end properties for backward compatibility for inputs
  72973. function GamepadCamera(name, position, scene) {
  72974. return _super.call(this, name, position, scene) || this;
  72975. }
  72976. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72977. //-- Begin properties for backward compatibility for inputs
  72978. get: function () {
  72979. var gamepad = this.inputs.attached["gamepad"];
  72980. if (gamepad)
  72981. return gamepad.gamepadAngularSensibility;
  72982. return 0;
  72983. },
  72984. set: function (value) {
  72985. var gamepad = this.inputs.attached["gamepad"];
  72986. if (gamepad)
  72987. gamepad.gamepadAngularSensibility = value;
  72988. },
  72989. enumerable: true,
  72990. configurable: true
  72991. });
  72992. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72993. get: function () {
  72994. var gamepad = this.inputs.attached["gamepad"];
  72995. if (gamepad)
  72996. return gamepad.gamepadMoveSensibility;
  72997. return 0;
  72998. },
  72999. set: function (value) {
  73000. var gamepad = this.inputs.attached["gamepad"];
  73001. if (gamepad)
  73002. gamepad.gamepadMoveSensibility = value;
  73003. },
  73004. enumerable: true,
  73005. configurable: true
  73006. });
  73007. GamepadCamera.prototype.getClassName = function () {
  73008. return "GamepadCamera";
  73009. };
  73010. return GamepadCamera;
  73011. }(BABYLON.UniversalCamera));
  73012. BABYLON.GamepadCamera = GamepadCamera;
  73013. })(BABYLON || (BABYLON = {}));
  73014. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73015. var BABYLON;
  73016. (function (BABYLON) {
  73017. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73018. function PostProcessRenderPipelineManager() {
  73019. this._renderPipelines = {};
  73020. }
  73021. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73022. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73023. };
  73024. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73025. if (unique === void 0) { unique = false; }
  73026. var renderPipeline = this._renderPipelines[renderPipelineName];
  73027. if (!renderPipeline) {
  73028. return;
  73029. }
  73030. renderPipeline._attachCameras(cameras, unique);
  73031. };
  73032. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73033. var renderPipeline = this._renderPipelines[renderPipelineName];
  73034. if (!renderPipeline) {
  73035. return;
  73036. }
  73037. renderPipeline._detachCameras(cameras);
  73038. };
  73039. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73040. var renderPipeline = this._renderPipelines[renderPipelineName];
  73041. if (!renderPipeline) {
  73042. return;
  73043. }
  73044. renderPipeline._enableEffect(renderEffectName, cameras);
  73045. };
  73046. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73047. var renderPipeline = this._renderPipelines[renderPipelineName];
  73048. if (!renderPipeline) {
  73049. return;
  73050. }
  73051. renderPipeline._disableEffect(renderEffectName, cameras);
  73052. };
  73053. PostProcessRenderPipelineManager.prototype.update = function () {
  73054. for (var renderPipelineName in this._renderPipelines) {
  73055. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73056. var pipeline = this._renderPipelines[renderPipelineName];
  73057. if (!pipeline.isSupported) {
  73058. pipeline.dispose();
  73059. delete this._renderPipelines[renderPipelineName];
  73060. }
  73061. else {
  73062. pipeline._update();
  73063. }
  73064. }
  73065. }
  73066. };
  73067. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73068. for (var renderPipelineName in this._renderPipelines) {
  73069. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73070. var pipeline = this._renderPipelines[renderPipelineName];
  73071. pipeline._rebuild();
  73072. }
  73073. }
  73074. };
  73075. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73076. for (var renderPipelineName in this._renderPipelines) {
  73077. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73078. var pipeline = this._renderPipelines[renderPipelineName];
  73079. pipeline.dispose();
  73080. }
  73081. }
  73082. };
  73083. return PostProcessRenderPipelineManager;
  73084. }());
  73085. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73086. })(BABYLON || (BABYLON = {}));
  73087. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73088. var BABYLON;
  73089. (function (BABYLON) {
  73090. /**
  73091. * This represents a set of one or more post processes in Babylon.
  73092. * A post process can be used to apply a shader to a texture after it is rendered.
  73093. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73094. */
  73095. var PostProcessRenderEffect = /** @class */ (function () {
  73096. /**
  73097. * Instantiates a post process render effect.
  73098. * A post process can be used to apply a shader to a texture after it is rendered.
  73099. * @param engine The engine the effect is tied to
  73100. * @param name The name of the effect
  73101. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73102. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73103. */
  73104. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73105. this._name = name;
  73106. this._singleInstance = singleInstance || true;
  73107. this._getPostProcesses = getPostProcesses;
  73108. this._cameras = {};
  73109. this._indicesForCamera = {};
  73110. this._postProcesses = {};
  73111. }
  73112. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73113. /**
  73114. * Checks if all the post processes in the effect are supported.
  73115. */
  73116. get: function () {
  73117. for (var index in this._postProcesses) {
  73118. if (this._postProcesses.hasOwnProperty(index)) {
  73119. var pps = this._postProcesses[index];
  73120. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73121. if (!pps[ppIndex].isSupported) {
  73122. return false;
  73123. }
  73124. }
  73125. }
  73126. }
  73127. return true;
  73128. },
  73129. enumerable: true,
  73130. configurable: true
  73131. });
  73132. /**
  73133. * Updates the current state of the effect
  73134. */
  73135. PostProcessRenderEffect.prototype._update = function () {
  73136. };
  73137. /**
  73138. * Attaches the effect on cameras
  73139. * @param cameras The camera to attach to.
  73140. */
  73141. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73142. var _this = this;
  73143. var cameraKey;
  73144. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73145. if (!cams) {
  73146. return;
  73147. }
  73148. for (var i = 0; i < cams.length; i++) {
  73149. var camera = cams[i];
  73150. var cameraName = camera.name;
  73151. if (this._singleInstance) {
  73152. cameraKey = 0;
  73153. }
  73154. else {
  73155. cameraKey = cameraName;
  73156. }
  73157. if (!this._postProcesses[cameraKey]) {
  73158. var postProcess = this._getPostProcesses();
  73159. if (postProcess) {
  73160. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73161. }
  73162. }
  73163. if (!this._indicesForCamera[cameraName]) {
  73164. this._indicesForCamera[cameraName] = [];
  73165. }
  73166. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73167. var index = camera.attachPostProcess(postProcess);
  73168. _this._indicesForCamera[cameraName].push(index);
  73169. });
  73170. if (!this._cameras[cameraName]) {
  73171. this._cameras[cameraName] = camera;
  73172. }
  73173. }
  73174. };
  73175. /**
  73176. * Detatches the effect on cameras
  73177. * @param cameras The camera to detatch from.
  73178. */
  73179. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73180. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73181. if (!cams) {
  73182. return;
  73183. }
  73184. for (var i = 0; i < cams.length; i++) {
  73185. var camera = cams[i];
  73186. var cameraName = camera.name;
  73187. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73188. camera.detachPostProcess(postProcess);
  73189. });
  73190. if (this._cameras[cameraName]) {
  73191. //this._indicesForCamera.splice(index, 1);
  73192. this._cameras[cameraName] = null;
  73193. }
  73194. }
  73195. };
  73196. /**
  73197. * Enables the effect on given cameras
  73198. * @param cameras The camera to enable.
  73199. */
  73200. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73201. var _this = this;
  73202. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73203. if (!cams) {
  73204. return;
  73205. }
  73206. for (var i = 0; i < cams.length; i++) {
  73207. var camera = cams[i];
  73208. var cameraName = camera.name;
  73209. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73210. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73211. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73212. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73213. });
  73214. }
  73215. }
  73216. }
  73217. };
  73218. /**
  73219. * Disables the effect on the given cameras
  73220. * @param cameras The camera to disable.
  73221. */
  73222. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73223. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73224. if (!cams) {
  73225. return;
  73226. }
  73227. for (var i = 0; i < cams.length; i++) {
  73228. var camera = cams[i];
  73229. var cameraName = camera.name;
  73230. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73231. camera.detachPostProcess(postProcess);
  73232. });
  73233. }
  73234. };
  73235. /**
  73236. * Gets a list of the post processes contained in the effect.
  73237. * @param camera The camera to get the post processes on.
  73238. * @returns The list of the post processes in the effect.
  73239. */
  73240. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73241. if (this._singleInstance) {
  73242. return this._postProcesses[0];
  73243. }
  73244. else {
  73245. if (!camera) {
  73246. return null;
  73247. }
  73248. return this._postProcesses[camera.name];
  73249. }
  73250. };
  73251. return PostProcessRenderEffect;
  73252. }());
  73253. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73254. })(BABYLON || (BABYLON = {}));
  73255. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73256. var BABYLON;
  73257. (function (BABYLON) {
  73258. var PostProcessRenderPipeline = /** @class */ (function () {
  73259. function PostProcessRenderPipeline(engine, name) {
  73260. this.engine = engine;
  73261. this._name = name;
  73262. this._renderEffects = {};
  73263. this._renderEffectsForIsolatedPass = new Array();
  73264. this._cameras = [];
  73265. }
  73266. PostProcessRenderPipeline.prototype.getClassName = function () {
  73267. return "PostProcessRenderPipeline";
  73268. };
  73269. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73270. get: function () {
  73271. for (var renderEffectName in this._renderEffects) {
  73272. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73273. if (!this._renderEffects[renderEffectName].isSupported) {
  73274. return false;
  73275. }
  73276. }
  73277. }
  73278. return true;
  73279. },
  73280. enumerable: true,
  73281. configurable: true
  73282. });
  73283. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73284. this._renderEffects[renderEffect._name] = renderEffect;
  73285. };
  73286. // private
  73287. PostProcessRenderPipeline.prototype._rebuild = function () {
  73288. };
  73289. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73290. var renderEffects = this._renderEffects[renderEffectName];
  73291. if (!renderEffects) {
  73292. return;
  73293. }
  73294. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73295. };
  73296. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73297. var renderEffects = this._renderEffects[renderEffectName];
  73298. if (!renderEffects) {
  73299. return;
  73300. }
  73301. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73302. };
  73303. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73304. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73305. if (!cams) {
  73306. return;
  73307. }
  73308. var indicesToDelete = [];
  73309. var i;
  73310. for (i = 0; i < cams.length; i++) {
  73311. var camera = cams[i];
  73312. var cameraName = camera.name;
  73313. if (this._cameras.indexOf(camera) === -1) {
  73314. this._cameras[cameraName] = camera;
  73315. }
  73316. else if (unique) {
  73317. indicesToDelete.push(i);
  73318. }
  73319. }
  73320. for (i = 0; i < indicesToDelete.length; i++) {
  73321. cameras.splice(indicesToDelete[i], 1);
  73322. }
  73323. for (var renderEffectName in this._renderEffects) {
  73324. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73325. this._renderEffects[renderEffectName]._attachCameras(cams);
  73326. }
  73327. }
  73328. };
  73329. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73330. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73331. if (!cams) {
  73332. return;
  73333. }
  73334. for (var renderEffectName in this._renderEffects) {
  73335. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73336. this._renderEffects[renderEffectName]._detachCameras(cams);
  73337. }
  73338. }
  73339. for (var i = 0; i < cams.length; i++) {
  73340. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73341. }
  73342. };
  73343. PostProcessRenderPipeline.prototype._update = function () {
  73344. for (var renderEffectName in this._renderEffects) {
  73345. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73346. this._renderEffects[renderEffectName]._update();
  73347. }
  73348. }
  73349. for (var i = 0; i < this._cameras.length; i++) {
  73350. var cameraName = this._cameras[i].name;
  73351. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73352. this._renderEffectsForIsolatedPass[cameraName]._update();
  73353. }
  73354. }
  73355. };
  73356. PostProcessRenderPipeline.prototype._reset = function () {
  73357. this._renderEffects = {};
  73358. this._renderEffectsForIsolatedPass = new Array();
  73359. };
  73360. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73361. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  73362. var effectKeys = Object.keys(this._renderEffects);
  73363. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73364. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73365. if (postProcesses) {
  73366. postProcesses[0].samples = sampleCount;
  73367. return true;
  73368. }
  73369. }
  73370. return false;
  73371. };
  73372. PostProcessRenderPipeline.prototype.dispose = function () {
  73373. // Must be implemented by children
  73374. };
  73375. __decorate([
  73376. BABYLON.serialize()
  73377. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73378. return PostProcessRenderPipeline;
  73379. }());
  73380. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73381. })(BABYLON || (BABYLON = {}));
  73382. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73383. var BABYLON;
  73384. (function (BABYLON) {
  73385. /**
  73386. * This represents a depth renderer in Babylon.
  73387. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73388. */
  73389. var DepthRenderer = /** @class */ (function () {
  73390. /**
  73391. * Instantiates a depth renderer
  73392. * @param scene The scene the renderer belongs to
  73393. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73394. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73395. */
  73396. function DepthRenderer(scene, type, camera) {
  73397. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73398. if (camera === void 0) { camera = null; }
  73399. var _this = this;
  73400. this._scene = scene;
  73401. this._camera = camera;
  73402. var engine = scene.getEngine();
  73403. // Render target
  73404. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73405. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73406. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73407. this._depthMap.refreshRate = 1;
  73408. this._depthMap.renderParticles = false;
  73409. this._depthMap.renderList = null;
  73410. // Camera to get depth map from to support multiple concurrent cameras
  73411. this._depthMap.activeCamera = this._camera;
  73412. this._depthMap.ignoreCameraViewport = true;
  73413. this._depthMap.useCameraPostProcesses = false;
  73414. // set default depth value to 1.0 (far away)
  73415. this._depthMap.onClearObservable.add(function (engine) {
  73416. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73417. });
  73418. // Custom render function
  73419. var renderSubMesh = function (subMesh) {
  73420. var mesh = subMesh.getRenderingMesh();
  73421. var scene = _this._scene;
  73422. var engine = scene.getEngine();
  73423. var material = subMesh.getMaterial();
  73424. if (!material) {
  73425. return;
  73426. }
  73427. // Culling and reverse (right handed system)
  73428. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73429. // Managing instances
  73430. var batch = mesh._getInstancesRenderList(subMesh._id);
  73431. if (batch.mustReturn) {
  73432. return;
  73433. }
  73434. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73435. var camera = _this._camera || scene.activeCamera;
  73436. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73437. engine.enableEffect(_this._effect);
  73438. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73439. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73440. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73441. // Alpha test
  73442. if (material && material.needAlphaTesting()) {
  73443. var alphaTexture = material.getAlphaTestTexture();
  73444. if (alphaTexture) {
  73445. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73446. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73447. }
  73448. }
  73449. // Bones
  73450. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73451. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73452. }
  73453. // Draw
  73454. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73455. }
  73456. };
  73457. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73458. var index;
  73459. if (depthOnlySubMeshes.length) {
  73460. engine.setColorWrite(false);
  73461. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73462. renderSubMesh(depthOnlySubMeshes.data[index]);
  73463. }
  73464. engine.setColorWrite(true);
  73465. }
  73466. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73467. renderSubMesh(opaqueSubMeshes.data[index]);
  73468. }
  73469. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73470. renderSubMesh(alphaTestSubMeshes.data[index]);
  73471. }
  73472. };
  73473. }
  73474. /**
  73475. * Creates the depth rendering effect and checks if the effect is ready.
  73476. * @param subMesh The submesh to be used to render the depth map of
  73477. * @param useInstances If multiple world instances should be used
  73478. * @returns if the depth renderer is ready to render the depth map
  73479. */
  73480. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73481. var material = subMesh.getMaterial();
  73482. if (material.disableDepthWrite) {
  73483. return false;
  73484. }
  73485. var defines = [];
  73486. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73487. var mesh = subMesh.getMesh();
  73488. // Alpha test
  73489. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73490. defines.push("#define ALPHATEST");
  73491. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73492. attribs.push(BABYLON.VertexBuffer.UVKind);
  73493. defines.push("#define UV1");
  73494. }
  73495. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73496. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73497. defines.push("#define UV2");
  73498. }
  73499. }
  73500. // Bones
  73501. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73502. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73503. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73504. if (mesh.numBoneInfluencers > 4) {
  73505. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73506. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73507. }
  73508. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73509. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73510. }
  73511. else {
  73512. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73513. }
  73514. // Instances
  73515. if (useInstances) {
  73516. defines.push("#define INSTANCES");
  73517. attribs.push("world0");
  73518. attribs.push("world1");
  73519. attribs.push("world2");
  73520. attribs.push("world3");
  73521. }
  73522. // Get correct effect
  73523. var join = defines.join("\n");
  73524. if (this._cachedDefines !== join) {
  73525. this._cachedDefines = join;
  73526. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73527. }
  73528. return this._effect.isReady();
  73529. };
  73530. /**
  73531. * Gets the texture which the depth map will be written to.
  73532. * @returns The depth map texture
  73533. */
  73534. DepthRenderer.prototype.getDepthMap = function () {
  73535. return this._depthMap;
  73536. };
  73537. /**
  73538. * Disposes of the depth renderer.
  73539. */
  73540. DepthRenderer.prototype.dispose = function () {
  73541. this._depthMap.dispose();
  73542. };
  73543. return DepthRenderer;
  73544. }());
  73545. BABYLON.DepthRenderer = DepthRenderer;
  73546. })(BABYLON || (BABYLON = {}));
  73547. //# sourceMappingURL=babylon.depthRenderer.js.map
  73548. var BABYLON;
  73549. (function (BABYLON) {
  73550. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73551. __extends(SSAORenderingPipeline, _super);
  73552. /**
  73553. * @constructor
  73554. * @param {string} name - The rendering pipeline name
  73555. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73556. * @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 }
  73557. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73558. */
  73559. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73560. var _this = _super.call(this, scene.getEngine(), name) || this;
  73561. // Members
  73562. /**
  73563. * The PassPostProcess id in the pipeline that contains the original scene color
  73564. */
  73565. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73566. /**
  73567. * The SSAO PostProcess id in the pipeline
  73568. */
  73569. _this.SSAORenderEffect = "SSAORenderEffect";
  73570. /**
  73571. * The horizontal blur PostProcess id in the pipeline
  73572. */
  73573. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73574. /**
  73575. * The vertical blur PostProcess id in the pipeline
  73576. */
  73577. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73578. /**
  73579. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73580. */
  73581. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73582. /**
  73583. * The output strength of the SSAO post-process. Default value is 1.0.
  73584. */
  73585. _this.totalStrength = 1.0;
  73586. /**
  73587. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73588. */
  73589. _this.radius = 0.0001;
  73590. /**
  73591. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73592. * Must not be equal to fallOff and superior to fallOff.
  73593. * Default value is 0.975
  73594. */
  73595. _this.area = 0.0075;
  73596. /**
  73597. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73598. * Must not be equal to area and inferior to area.
  73599. * Default value is 0.0
  73600. */
  73601. _this.fallOff = 0.000001;
  73602. /**
  73603. * The base color of the SSAO post-process
  73604. * The final result is "base + ssao" between [0, 1]
  73605. */
  73606. _this.base = 0.5;
  73607. _this._firstUpdate = true;
  73608. _this._scene = scene;
  73609. // Set up assets
  73610. _this._createRandomTexture();
  73611. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73612. var ssaoRatio = ratio.ssaoRatio || ratio;
  73613. var combineRatio = ratio.combineRatio || ratio;
  73614. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73615. _this._createSSAOPostProcess(ssaoRatio);
  73616. _this._createBlurPostProcess(ssaoRatio);
  73617. _this._createSSAOCombinePostProcess(combineRatio);
  73618. // Set up pipeline
  73619. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73620. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73621. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73622. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73623. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73624. // Finish
  73625. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73626. if (cameras)
  73627. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73628. return _this;
  73629. }
  73630. // Public Methods
  73631. /**
  73632. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73633. */
  73634. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73635. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73636. for (var i = 0; i < this._scene.cameras.length; i++) {
  73637. var camera = this._scene.cameras[i];
  73638. this._originalColorPostProcess.dispose(camera);
  73639. this._ssaoPostProcess.dispose(camera);
  73640. this._blurHPostProcess.dispose(camera);
  73641. this._blurVPostProcess.dispose(camera);
  73642. this._ssaoCombinePostProcess.dispose(camera);
  73643. }
  73644. this._randomTexture.dispose();
  73645. if (disableDepthRender)
  73646. this._scene.disableDepthRenderer();
  73647. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73648. _super.prototype.dispose.call(this);
  73649. };
  73650. // Private Methods
  73651. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73652. var _this = this;
  73653. var size = 16;
  73654. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73655. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73656. this._blurHPostProcess.onActivateObservable.add(function () {
  73657. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73658. _this._blurHPostProcess.kernel = size * dw;
  73659. });
  73660. this._blurVPostProcess.onActivateObservable.add(function () {
  73661. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73662. _this._blurVPostProcess.kernel = size * dw;
  73663. });
  73664. };
  73665. SSAORenderingPipeline.prototype._rebuild = function () {
  73666. this._firstUpdate = true;
  73667. _super.prototype._rebuild.call(this);
  73668. };
  73669. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73670. var _this = this;
  73671. var numSamples = 16;
  73672. var sampleSphere = [
  73673. 0.5381, 0.1856, -0.4319,
  73674. 0.1379, 0.2486, 0.4430,
  73675. 0.3371, 0.5679, -0.0057,
  73676. -0.6999, -0.0451, -0.0019,
  73677. 0.0689, -0.1598, -0.8547,
  73678. 0.0560, 0.0069, -0.1843,
  73679. -0.0146, 0.1402, 0.0762,
  73680. 0.0100, -0.1924, -0.0344,
  73681. -0.3577, -0.5301, -0.4358,
  73682. -0.3169, 0.1063, 0.0158,
  73683. 0.0103, -0.5869, 0.0046,
  73684. -0.0897, -0.4940, 0.3287,
  73685. 0.7119, -0.0154, -0.0918,
  73686. -0.0533, 0.0596, -0.5411,
  73687. 0.0352, -0.0631, 0.5460,
  73688. -0.4776, 0.2847, -0.0271
  73689. ];
  73690. var samplesFactor = 1.0 / numSamples;
  73691. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73692. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73693. "area", "fallOff", "base", "range", "viewport"
  73694. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73695. this._ssaoPostProcess.onApply = function (effect) {
  73696. if (_this._firstUpdate) {
  73697. effect.setArray3("sampleSphere", sampleSphere);
  73698. effect.setFloat("samplesFactor", samplesFactor);
  73699. effect.setFloat("randTextureTiles", 4.0);
  73700. }
  73701. effect.setFloat("totalStrength", _this.totalStrength);
  73702. effect.setFloat("radius", _this.radius);
  73703. effect.setFloat("area", _this.area);
  73704. effect.setFloat("fallOff", _this.fallOff);
  73705. effect.setFloat("base", _this.base);
  73706. effect.setTexture("textureSampler", _this._depthTexture);
  73707. effect.setTexture("randomSampler", _this._randomTexture);
  73708. };
  73709. };
  73710. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73711. var _this = this;
  73712. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73713. this._ssaoCombinePostProcess.onApply = function (effect) {
  73714. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73715. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73716. };
  73717. };
  73718. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73719. var size = 512;
  73720. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73721. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73722. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73723. var context = this._randomTexture.getContext();
  73724. var rand = function (min, max) {
  73725. return Math.random() * (max - min) + min;
  73726. };
  73727. var randVector = BABYLON.Vector3.Zero();
  73728. for (var x = 0; x < size; x++) {
  73729. for (var y = 0; y < size; y++) {
  73730. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73731. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73732. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73733. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73734. context.fillRect(x, y, 1, 1);
  73735. }
  73736. }
  73737. this._randomTexture.update(false);
  73738. };
  73739. __decorate([
  73740. BABYLON.serialize()
  73741. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73742. __decorate([
  73743. BABYLON.serialize()
  73744. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73745. __decorate([
  73746. BABYLON.serialize()
  73747. ], SSAORenderingPipeline.prototype, "area", void 0);
  73748. __decorate([
  73749. BABYLON.serialize()
  73750. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73751. __decorate([
  73752. BABYLON.serialize()
  73753. ], SSAORenderingPipeline.prototype, "base", void 0);
  73754. return SSAORenderingPipeline;
  73755. }(BABYLON.PostProcessRenderPipeline));
  73756. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73757. })(BABYLON || (BABYLON = {}));
  73758. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73759. var BABYLON;
  73760. (function (BABYLON) {
  73761. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73762. __extends(SSAO2RenderingPipeline, _super);
  73763. /**
  73764. * @constructor
  73765. * @param {string} name - The rendering pipeline name
  73766. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73767. * @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 }
  73768. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73769. */
  73770. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73771. var _this = _super.call(this, scene.getEngine(), name) || this;
  73772. // Members
  73773. /**
  73774. * The PassPostProcess id in the pipeline that contains the original scene color
  73775. */
  73776. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73777. /**
  73778. * The SSAO PostProcess id in the pipeline
  73779. */
  73780. _this.SSAORenderEffect = "SSAORenderEffect";
  73781. /**
  73782. * The horizontal blur PostProcess id in the pipeline
  73783. */
  73784. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73785. /**
  73786. * The vertical blur PostProcess id in the pipeline
  73787. */
  73788. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73789. /**
  73790. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73791. */
  73792. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73793. /**
  73794. * The output strength of the SSAO post-process. Default value is 1.0.
  73795. */
  73796. _this.totalStrength = 1.0;
  73797. /**
  73798. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73799. */
  73800. _this.maxZ = 100.0;
  73801. /**
  73802. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73803. */
  73804. _this.minZAspect = 0.2;
  73805. /**
  73806. * Number of samples used for the SSAO calculations. Default value is 8
  73807. */
  73808. _this._samples = 8;
  73809. /**
  73810. * Are we using bilateral blur ?
  73811. */
  73812. _this._expensiveBlur = true;
  73813. /**
  73814. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73815. */
  73816. _this.radius = 2.0;
  73817. /**
  73818. * The base color of the SSAO post-process
  73819. * The final result is "base + ssao" between [0, 1]
  73820. */
  73821. _this.base = 0.1;
  73822. _this._firstUpdate = true;
  73823. _this._scene = scene;
  73824. _this._ratio = ratio;
  73825. if (!_this.isSupported) {
  73826. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73827. return _this;
  73828. }
  73829. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73830. var blurRatio = _this._ratio.blurRatio || ratio;
  73831. // Set up assets
  73832. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73833. _this._createRandomTexture();
  73834. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73835. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73836. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73837. _this._createSSAOPostProcess(1.0);
  73838. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73839. _this._createSSAOCombinePostProcess(blurRatio);
  73840. // Set up pipeline
  73841. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73842. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73843. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73844. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73845. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73846. // Finish
  73847. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73848. if (cameras)
  73849. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73850. return _this;
  73851. }
  73852. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73853. get: function () {
  73854. return this._samples;
  73855. },
  73856. set: function (n) {
  73857. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73858. this._samples = n;
  73859. this._sampleSphere = this._generateHemisphere();
  73860. this._firstUpdate = true;
  73861. },
  73862. enumerable: true,
  73863. configurable: true
  73864. });
  73865. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73866. get: function () {
  73867. return this._expensiveBlur;
  73868. },
  73869. set: function (b) {
  73870. 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"]);
  73871. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73872. this._expensiveBlur = b;
  73873. this._firstUpdate = true;
  73874. },
  73875. enumerable: true,
  73876. configurable: true
  73877. });
  73878. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73879. /**
  73880. * Support test.
  73881. */
  73882. get: function () {
  73883. var engine = BABYLON.Engine.LastCreatedEngine;
  73884. if (!engine) {
  73885. return false;
  73886. }
  73887. return engine.getCaps().drawBuffersExtension;
  73888. },
  73889. enumerable: true,
  73890. configurable: true
  73891. });
  73892. // Public Methods
  73893. /**
  73894. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73895. */
  73896. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73897. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73898. for (var i = 0; i < this._scene.cameras.length; i++) {
  73899. var camera = this._scene.cameras[i];
  73900. this._originalColorPostProcess.dispose(camera);
  73901. this._ssaoPostProcess.dispose(camera);
  73902. this._blurHPostProcess.dispose(camera);
  73903. this._blurVPostProcess.dispose(camera);
  73904. this._ssaoCombinePostProcess.dispose(camera);
  73905. }
  73906. this._randomTexture.dispose();
  73907. if (disableGeometryBufferRenderer)
  73908. this._scene.disableGeometryBufferRenderer();
  73909. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73910. _super.prototype.dispose.call(this);
  73911. };
  73912. // Private Methods
  73913. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73914. var _this = this;
  73915. this._samplerOffsets = [];
  73916. var expensive = this.expensiveBlur;
  73917. for (var i = -8; i < 8; i++) {
  73918. this._samplerOffsets.push(i * 2 + 0.5);
  73919. }
  73920. 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");
  73921. this._blurHPostProcess.onApply = function (effect) {
  73922. if (!_this._scene.activeCamera) {
  73923. return;
  73924. }
  73925. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73926. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73927. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73928. effect.setFloat("radius", _this.radius);
  73929. effect.setTexture("depthSampler", _this._depthTexture);
  73930. if (_this._firstUpdate) {
  73931. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73932. }
  73933. };
  73934. 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");
  73935. this._blurVPostProcess.onApply = function (effect) {
  73936. if (!_this._scene.activeCamera) {
  73937. return;
  73938. }
  73939. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73940. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73941. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73942. effect.setFloat("radius", _this.radius);
  73943. effect.setTexture("depthSampler", _this._depthTexture);
  73944. if (_this._firstUpdate) {
  73945. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73946. _this._firstUpdate = false;
  73947. }
  73948. };
  73949. };
  73950. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73951. this._firstUpdate = true;
  73952. _super.prototype._rebuild.call(this);
  73953. };
  73954. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73955. var numSamples = this.samples;
  73956. var result = [];
  73957. var vector, scale;
  73958. var rand = function (min, max) {
  73959. return Math.random() * (max - min) + min;
  73960. };
  73961. var i = 0;
  73962. while (i < numSamples) {
  73963. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73964. vector.normalize();
  73965. scale = i / numSamples;
  73966. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73967. vector.scaleInPlace(scale);
  73968. result.push(vector.x, vector.y, vector.z);
  73969. i++;
  73970. }
  73971. return result;
  73972. };
  73973. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73974. var _this = this;
  73975. var numSamples = this.samples;
  73976. this._sampleSphere = this._generateHemisphere();
  73977. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73978. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73979. "base", "range", "projection", "near", "far", "texelSize",
  73980. "xViewport", "yViewport", "maxZ", "minZAspect"
  73981. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73982. this._ssaoPostProcess.onApply = function (effect) {
  73983. if (_this._firstUpdate) {
  73984. effect.setArray3("sampleSphere", _this._sampleSphere);
  73985. effect.setFloat("randTextureTiles", 4.0);
  73986. }
  73987. if (!_this._scene.activeCamera) {
  73988. return;
  73989. }
  73990. effect.setFloat("samplesFactor", 1 / _this.samples);
  73991. effect.setFloat("totalStrength", _this.totalStrength);
  73992. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73993. effect.setFloat("radius", _this.radius);
  73994. effect.setFloat("maxZ", _this.maxZ);
  73995. effect.setFloat("minZAspect", _this.minZAspect);
  73996. effect.setFloat("base", _this.base);
  73997. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73998. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73999. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74000. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74001. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74002. effect.setTexture("textureSampler", _this._depthTexture);
  74003. effect.setTexture("normalSampler", _this._normalTexture);
  74004. effect.setTexture("randomSampler", _this._randomTexture);
  74005. };
  74006. };
  74007. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74008. var _this = this;
  74009. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74010. this._ssaoCombinePostProcess.onApply = function (effect) {
  74011. var viewport = _this._scene.activeCamera.viewport;
  74012. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74013. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74014. };
  74015. };
  74016. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74017. var size = 512;
  74018. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74019. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74020. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74021. var context = this._randomTexture.getContext();
  74022. var rand = function (min, max) {
  74023. return Math.random() * (max - min) + min;
  74024. };
  74025. var randVector = BABYLON.Vector3.Zero();
  74026. for (var x = 0; x < size; x++) {
  74027. for (var y = 0; y < size; y++) {
  74028. randVector.x = rand(0.0, 1.0);
  74029. randVector.y = rand(0.0, 1.0);
  74030. randVector.z = 0.0;
  74031. randVector.normalize();
  74032. randVector.scaleInPlace(255);
  74033. randVector.x = Math.floor(randVector.x);
  74034. randVector.y = Math.floor(randVector.y);
  74035. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74036. context.fillRect(x, y, 1, 1);
  74037. }
  74038. }
  74039. this._randomTexture.update(false);
  74040. };
  74041. /**
  74042. * Serialize the rendering pipeline (Used when exporting)
  74043. * @returns the serialized object
  74044. */
  74045. SSAO2RenderingPipeline.prototype.serialize = function () {
  74046. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74047. serializationObject.customType = "SSAO2RenderingPipeline";
  74048. return serializationObject;
  74049. };
  74050. /**
  74051. * Parse the serialized pipeline
  74052. * @param source Source pipeline.
  74053. * @param scene The scene to load the pipeline to.
  74054. * @param rootUrl The URL of the serialized pipeline.
  74055. * @returns An instantiated pipeline from the serialized object.
  74056. */
  74057. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74058. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74059. };
  74060. __decorate([
  74061. BABYLON.serialize()
  74062. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74063. __decorate([
  74064. BABYLON.serialize()
  74065. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74066. __decorate([
  74067. BABYLON.serialize()
  74068. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74069. __decorate([
  74070. BABYLON.serialize("samples")
  74071. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74072. __decorate([
  74073. BABYLON.serialize()
  74074. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74075. __decorate([
  74076. BABYLON.serialize("expensiveBlur")
  74077. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74078. __decorate([
  74079. BABYLON.serialize()
  74080. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74081. __decorate([
  74082. BABYLON.serialize()
  74083. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74084. return SSAO2RenderingPipeline;
  74085. }(BABYLON.PostProcessRenderPipeline));
  74086. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74087. })(BABYLON || (BABYLON = {}));
  74088. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74089. // BABYLON.JS Chromatic Aberration GLSL Shader
  74090. // Author: Olivier Guyot
  74091. // Separates very slightly R, G and B colors on the edges of the screen
  74092. // Inspired by Francois Tarlier & Martins Upitis
  74093. var BABYLON;
  74094. (function (BABYLON) {
  74095. var LensRenderingPipeline = /** @class */ (function (_super) {
  74096. __extends(LensRenderingPipeline, _super);
  74097. /**
  74098. * @constructor
  74099. *
  74100. * Effect parameters are as follow:
  74101. * {
  74102. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74103. * edge_blur: number; // from 0 to x (1 for realism)
  74104. * distortion: number; // from 0 to x (1 for realism)
  74105. * grain_amount: number; // from 0 to 1
  74106. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74107. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74108. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74109. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74110. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74111. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74112. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74113. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74114. * }
  74115. * Note: if an effect parameter is unset, effect is disabled
  74116. *
  74117. * @param {string} name - The rendering pipeline name
  74118. * @param {object} parameters - An object containing all parameters (see above)
  74119. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74120. * @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)
  74121. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74122. */
  74123. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74124. if (ratio === void 0) { ratio = 1.0; }
  74125. var _this = _super.call(this, scene.getEngine(), name) || this;
  74126. // Lens effects can be of the following:
  74127. // - chromatic aberration (slight shift of RGB colors)
  74128. // - blur on the edge of the lens
  74129. // - lens distortion
  74130. // - depth-of-field blur & highlights enhancing
  74131. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74132. // - grain effect (noise or custom texture)
  74133. // Two additional texture samplers are needed:
  74134. // - depth map (for depth-of-field)
  74135. // - grain texture
  74136. /**
  74137. * The chromatic aberration PostProcess id in the pipeline
  74138. */
  74139. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74140. /**
  74141. * The highlights enhancing PostProcess id in the pipeline
  74142. */
  74143. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74144. /**
  74145. * The depth-of-field PostProcess id in the pipeline
  74146. */
  74147. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74148. _this._scene = scene;
  74149. // Fetch texture samplers
  74150. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74151. if (parameters.grain_texture) {
  74152. _this._grainTexture = parameters.grain_texture;
  74153. }
  74154. else {
  74155. _this._createGrainTexture();
  74156. }
  74157. // save parameters
  74158. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74159. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74160. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74161. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74162. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74163. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74164. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74165. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74166. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74167. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74168. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74169. // Create effects
  74170. _this._createChromaticAberrationPostProcess(ratio);
  74171. _this._createHighlightsPostProcess(ratio);
  74172. _this._createDepthOfFieldPostProcess(ratio / 4);
  74173. // Set up pipeline
  74174. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74175. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74176. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74177. if (_this._highlightsGain === -1) {
  74178. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74179. }
  74180. // Finish
  74181. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74182. if (cameras) {
  74183. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74184. }
  74185. return _this;
  74186. }
  74187. // public methods (self explanatory)
  74188. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74189. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74190. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74191. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74192. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74193. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74194. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74195. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74196. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74197. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74198. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74199. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74200. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74201. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74202. };
  74203. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74204. this._highlightsPostProcess.updateEffect();
  74205. };
  74206. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74207. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74208. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74209. this._highlightsGain = amount;
  74210. };
  74211. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74212. if (this._highlightsGain === -1) {
  74213. this._highlightsGain = 1.0;
  74214. }
  74215. this._highlightsThreshold = amount;
  74216. };
  74217. LensRenderingPipeline.prototype.disableHighlights = function () {
  74218. this._highlightsGain = -1;
  74219. };
  74220. /**
  74221. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74222. */
  74223. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74224. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74225. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74226. this._chromaticAberrationPostProcess = null;
  74227. this._highlightsPostProcess = null;
  74228. this._depthOfFieldPostProcess = null;
  74229. this._grainTexture.dispose();
  74230. if (disableDepthRender)
  74231. this._scene.disableDepthRenderer();
  74232. };
  74233. // colors shifting and distortion
  74234. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74235. var _this = this;
  74236. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74237. [], // samplers
  74238. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74239. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74240. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74241. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74242. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74243. effect.setFloat('radialIntensity', 1);
  74244. effect.setFloat2('direction', 17, 17);
  74245. effect.setFloat2('centerPosition', 0.5, 0.5);
  74246. };
  74247. };
  74248. // highlights enhancing
  74249. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74250. var _this = this;
  74251. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74252. [], // samplers
  74253. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74254. this._highlightsPostProcess.onApply = function (effect) {
  74255. effect.setFloat('gain', _this._highlightsGain);
  74256. effect.setFloat('threshold', _this._highlightsThreshold);
  74257. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74258. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74259. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74260. };
  74261. };
  74262. // colors shifting and distortion
  74263. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74264. var _this = this;
  74265. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74266. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74267. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74268. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74269. this._depthOfFieldPostProcess.onApply = function (effect) {
  74270. effect.setTexture("depthSampler", _this._depthTexture);
  74271. effect.setTexture("grainSampler", _this._grainTexture);
  74272. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74273. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74274. effect.setFloat('grain_amount', _this._grainAmount);
  74275. effect.setBool('blur_noise', _this._blurNoise);
  74276. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74277. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74278. effect.setFloat('distortion', _this._distortion);
  74279. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74280. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74281. effect.setFloat('aperture', _this._dofAperture);
  74282. effect.setFloat('darken', _this._dofDarken);
  74283. effect.setFloat('edge_blur', _this._edgeBlur);
  74284. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74285. if (_this._scene.activeCamera) {
  74286. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74287. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74288. }
  74289. };
  74290. };
  74291. // creates a black and white random noise texture, 512x512
  74292. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74293. var size = 512;
  74294. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74295. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74296. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74297. var context = this._grainTexture.getContext();
  74298. var rand = function (min, max) {
  74299. return Math.random() * (max - min) + min;
  74300. };
  74301. var value;
  74302. for (var x = 0; x < size; x++) {
  74303. for (var y = 0; y < size; y++) {
  74304. value = Math.floor(rand(0.42, 0.58) * 255);
  74305. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74306. context.fillRect(x, y, 1, 1);
  74307. }
  74308. }
  74309. this._grainTexture.update(false);
  74310. };
  74311. return LensRenderingPipeline;
  74312. }(BABYLON.PostProcessRenderPipeline));
  74313. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74314. })(BABYLON || (BABYLON = {}));
  74315. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74316. var BABYLON;
  74317. (function (BABYLON) {
  74318. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74319. __extends(StandardRenderingPipeline, _super);
  74320. /**
  74321. * @constructor
  74322. * @param {string} name - The rendering pipeline name
  74323. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74324. * @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)
  74325. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74326. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74327. */
  74328. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74329. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74330. var _this = _super.call(this, scene.getEngine(), name) || this;
  74331. _this.downSampleX4PostProcess = null;
  74332. _this.brightPassPostProcess = null;
  74333. _this.blurHPostProcesses = [];
  74334. _this.blurVPostProcesses = [];
  74335. _this.textureAdderPostProcess = null;
  74336. _this.volumetricLightPostProcess = null;
  74337. _this.volumetricLightSmoothXPostProcess = null;
  74338. _this.volumetricLightSmoothYPostProcess = null;
  74339. _this.volumetricLightMergePostProces = null;
  74340. _this.volumetricLightFinalPostProcess = null;
  74341. _this.luminancePostProcess = null;
  74342. _this.luminanceDownSamplePostProcesses = [];
  74343. _this.hdrPostProcess = null;
  74344. _this.textureAdderFinalPostProcess = null;
  74345. _this.lensFlareFinalPostProcess = null;
  74346. _this.hdrFinalPostProcess = null;
  74347. _this.lensFlarePostProcess = null;
  74348. _this.lensFlareComposePostProcess = null;
  74349. _this.motionBlurPostProcess = null;
  74350. _this.depthOfFieldPostProcess = null;
  74351. // Values
  74352. _this.brightThreshold = 1.0;
  74353. _this.blurWidth = 512.0;
  74354. _this.horizontalBlur = false;
  74355. _this.exposure = 1.0;
  74356. _this.lensTexture = null;
  74357. _this.volumetricLightCoefficient = 0.2;
  74358. _this.volumetricLightPower = 4.0;
  74359. _this.volumetricLightBlurScale = 64.0;
  74360. _this.sourceLight = null;
  74361. _this.hdrMinimumLuminance = 1.0;
  74362. _this.hdrDecreaseRate = 0.5;
  74363. _this.hdrIncreaseRate = 0.5;
  74364. _this.lensColorTexture = null;
  74365. _this.lensFlareStrength = 20.0;
  74366. _this.lensFlareGhostDispersal = 1.4;
  74367. _this.lensFlareHaloWidth = 0.7;
  74368. _this.lensFlareDistortionStrength = 16.0;
  74369. _this.lensStarTexture = null;
  74370. _this.lensFlareDirtTexture = null;
  74371. _this.depthOfFieldDistance = 10.0;
  74372. _this.depthOfFieldBlurWidth = 64.0;
  74373. _this.motionStrength = 1.0;
  74374. // IAnimatable
  74375. _this.animations = [];
  74376. _this._currentDepthOfFieldSource = null;
  74377. _this._hdrCurrentLuminance = 1.0;
  74378. // Getters and setters
  74379. _this._bloomEnabled = true;
  74380. _this._depthOfFieldEnabled = false;
  74381. _this._vlsEnabled = false;
  74382. _this._lensFlareEnabled = false;
  74383. _this._hdrEnabled = false;
  74384. _this._motionBlurEnabled = false;
  74385. _this._motionBlurSamples = 64.0;
  74386. _this._volumetricLightStepsCount = 50.0;
  74387. _this._cameras = cameras || [];
  74388. // Initialize
  74389. _this._scene = scene;
  74390. _this._basePostProcess = originalPostProcess;
  74391. _this._ratio = ratio;
  74392. // Misc
  74393. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74394. // Finish
  74395. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74396. _this._buildPipeline();
  74397. return _this;
  74398. }
  74399. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74400. get: function () {
  74401. return this._bloomEnabled;
  74402. },
  74403. set: function (enabled) {
  74404. if (this._bloomEnabled === enabled) {
  74405. return;
  74406. }
  74407. this._bloomEnabled = enabled;
  74408. this._buildPipeline();
  74409. },
  74410. enumerable: true,
  74411. configurable: true
  74412. });
  74413. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74414. get: function () {
  74415. return this._depthOfFieldEnabled;
  74416. },
  74417. set: function (enabled) {
  74418. if (this._depthOfFieldEnabled === enabled) {
  74419. return;
  74420. }
  74421. this._depthOfFieldEnabled = enabled;
  74422. this._buildPipeline();
  74423. },
  74424. enumerable: true,
  74425. configurable: true
  74426. });
  74427. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74428. get: function () {
  74429. return this._lensFlareEnabled;
  74430. },
  74431. set: function (enabled) {
  74432. if (this._lensFlareEnabled === enabled) {
  74433. return;
  74434. }
  74435. this._lensFlareEnabled = enabled;
  74436. this._buildPipeline();
  74437. },
  74438. enumerable: true,
  74439. configurable: true
  74440. });
  74441. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74442. get: function () {
  74443. return this._hdrEnabled;
  74444. },
  74445. set: function (enabled) {
  74446. if (this._hdrEnabled === enabled) {
  74447. return;
  74448. }
  74449. this._hdrEnabled = enabled;
  74450. this._buildPipeline();
  74451. },
  74452. enumerable: true,
  74453. configurable: true
  74454. });
  74455. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74456. get: function () {
  74457. return this._vlsEnabled;
  74458. },
  74459. set: function (enabled) {
  74460. if (this._vlsEnabled === enabled) {
  74461. return;
  74462. }
  74463. if (enabled) {
  74464. var geometry = this._scene.enableGeometryBufferRenderer();
  74465. if (!geometry) {
  74466. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74467. return;
  74468. }
  74469. }
  74470. this._vlsEnabled = enabled;
  74471. this._buildPipeline();
  74472. },
  74473. enumerable: true,
  74474. configurable: true
  74475. });
  74476. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74477. get: function () {
  74478. return this._motionBlurEnabled;
  74479. },
  74480. set: function (enabled) {
  74481. if (this._motionBlurEnabled === enabled) {
  74482. return;
  74483. }
  74484. this._motionBlurEnabled = enabled;
  74485. this._buildPipeline();
  74486. },
  74487. enumerable: true,
  74488. configurable: true
  74489. });
  74490. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74491. get: function () {
  74492. return this._volumetricLightStepsCount;
  74493. },
  74494. set: function (count) {
  74495. if (this.volumetricLightPostProcess) {
  74496. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74497. }
  74498. this._volumetricLightStepsCount = count;
  74499. },
  74500. enumerable: true,
  74501. configurable: true
  74502. });
  74503. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74504. get: function () {
  74505. return this._motionBlurSamples;
  74506. },
  74507. set: function (samples) {
  74508. if (this.motionBlurPostProcess) {
  74509. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74510. }
  74511. this._motionBlurSamples = samples;
  74512. },
  74513. enumerable: true,
  74514. configurable: true
  74515. });
  74516. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74517. var _this = this;
  74518. var ratio = this._ratio;
  74519. var scene = this._scene;
  74520. this._disposePostProcesses();
  74521. this._reset();
  74522. // Create pass post-process
  74523. if (!this._basePostProcess) {
  74524. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74525. this.originalPostProcess.onApply = function (effect) {
  74526. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74527. };
  74528. }
  74529. else {
  74530. this.originalPostProcess = this._basePostProcess;
  74531. }
  74532. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74533. this._currentDepthOfFieldSource = this.originalPostProcess;
  74534. if (this._bloomEnabled) {
  74535. // Create down sample X4 post-process
  74536. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74537. // Create bright pass post-process
  74538. this._createBrightPassPostProcess(scene, ratio / 2);
  74539. // Create gaussian blur post-processes (down sampling blurs)
  74540. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74541. // Create texture adder post-process
  74542. this._createTextureAdderPostProcess(scene, ratio);
  74543. // Create depth-of-field source post-process
  74544. 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);
  74545. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74546. }
  74547. if (this._vlsEnabled) {
  74548. // Create volumetric light
  74549. this._createVolumetricLightPostProcess(scene, ratio);
  74550. // Create volumetric light final post-process
  74551. 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);
  74552. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74553. }
  74554. if (this._lensFlareEnabled) {
  74555. // Create lens flare post-process
  74556. this._createLensFlarePostProcess(scene, ratio);
  74557. // Create depth-of-field source post-process post lens-flare and disable it now
  74558. 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);
  74559. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74560. }
  74561. if (this._hdrEnabled) {
  74562. // Create luminance
  74563. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74564. // Create HDR
  74565. this._createHdrPostProcess(scene, ratio);
  74566. // Create depth-of-field source post-process post hdr and disable it now
  74567. 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);
  74568. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74569. }
  74570. if (this._depthOfFieldEnabled) {
  74571. // Create gaussian blur used by depth-of-field
  74572. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74573. // Create depth-of-field post-process
  74574. this._createDepthOfFieldPostProcess(scene, ratio);
  74575. }
  74576. if (this._motionBlurEnabled) {
  74577. // Create motion blur post-process
  74578. this._createMotionBlurPostProcess(scene, ratio);
  74579. }
  74580. if (this._cameras !== null) {
  74581. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74582. }
  74583. };
  74584. // Down Sample X4 Post-Processs
  74585. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74586. var _this = this;
  74587. var downSampleX4Offsets = new Array(32);
  74588. 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);
  74589. this.downSampleX4PostProcess.onApply = function (effect) {
  74590. var id = 0;
  74591. var width = _this.downSampleX4PostProcess.width;
  74592. var height = _this.downSampleX4PostProcess.height;
  74593. for (var i = -2; i < 2; i++) {
  74594. for (var j = -2; j < 2; j++) {
  74595. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74596. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74597. id += 2;
  74598. }
  74599. }
  74600. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74601. };
  74602. // Add to pipeline
  74603. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74604. };
  74605. // Brightpass Post-Process
  74606. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74607. var _this = this;
  74608. var brightOffsets = new Array(8);
  74609. 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);
  74610. this.brightPassPostProcess.onApply = function (effect) {
  74611. var sU = (1.0 / _this.brightPassPostProcess.width);
  74612. var sV = (1.0 / _this.brightPassPostProcess.height);
  74613. brightOffsets[0] = -0.5 * sU;
  74614. brightOffsets[1] = 0.5 * sV;
  74615. brightOffsets[2] = 0.5 * sU;
  74616. brightOffsets[3] = 0.5 * sV;
  74617. brightOffsets[4] = -0.5 * sU;
  74618. brightOffsets[5] = -0.5 * sV;
  74619. brightOffsets[6] = 0.5 * sU;
  74620. brightOffsets[7] = -0.5 * sV;
  74621. effect.setArray2("dsOffsets", brightOffsets);
  74622. effect.setFloat("brightThreshold", _this.brightThreshold);
  74623. };
  74624. // Add to pipeline
  74625. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74626. };
  74627. // Create blur H&V post-processes
  74628. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74629. var _this = this;
  74630. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74631. var engine = scene.getEngine();
  74632. 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);
  74633. 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);
  74634. blurX.onActivateObservable.add(function () {
  74635. var dw = blurX.width / engine.getRenderWidth();
  74636. blurX.kernel = _this[blurWidthKey] * dw;
  74637. });
  74638. blurY.onActivateObservable.add(function () {
  74639. var dw = blurY.height / engine.getRenderHeight();
  74640. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74641. });
  74642. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74643. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74644. this.blurHPostProcesses.push(blurX);
  74645. this.blurVPostProcesses.push(blurY);
  74646. };
  74647. // Create texture adder post-process
  74648. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74649. var _this = this;
  74650. 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);
  74651. this.textureAdderPostProcess.onApply = function (effect) {
  74652. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74653. effect.setTexture("lensSampler", _this.lensTexture);
  74654. effect.setFloat("exposure", _this.exposure);
  74655. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74656. };
  74657. // Add to pipeline
  74658. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74659. };
  74660. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74661. var _this = this;
  74662. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74663. geometryRenderer.enablePosition = true;
  74664. var geometry = geometryRenderer.getGBuffer();
  74665. // Base post-process
  74666. 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));
  74667. var depthValues = BABYLON.Vector2.Zero();
  74668. this.volumetricLightPostProcess.onApply = function (effect) {
  74669. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74670. var generator = _this.sourceLight.getShadowGenerator();
  74671. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74672. effect.setTexture("positionSampler", geometry.textures[2]);
  74673. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74674. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74675. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74676. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74677. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74678. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74679. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74680. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74681. effect.setVector2("depthValues", depthValues);
  74682. }
  74683. };
  74684. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74685. // Smooth
  74686. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74687. // Merge
  74688. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74689. this.volumetricLightMergePostProces.onApply = function (effect) {
  74690. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74691. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74692. };
  74693. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74694. };
  74695. // Create luminance
  74696. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74697. var _this = this;
  74698. // Create luminance
  74699. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74700. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74701. var offsets = [];
  74702. this.luminancePostProcess.onApply = function (effect) {
  74703. var sU = (1.0 / _this.luminancePostProcess.width);
  74704. var sV = (1.0 / _this.luminancePostProcess.height);
  74705. offsets[0] = -0.5 * sU;
  74706. offsets[1] = 0.5 * sV;
  74707. offsets[2] = 0.5 * sU;
  74708. offsets[3] = 0.5 * sV;
  74709. offsets[4] = -0.5 * sU;
  74710. offsets[5] = -0.5 * sV;
  74711. offsets[6] = 0.5 * sU;
  74712. offsets[7] = -0.5 * sV;
  74713. effect.setArray2("lumOffsets", offsets);
  74714. };
  74715. // Add to pipeline
  74716. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74717. // Create down sample luminance
  74718. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74719. var size = Math.pow(3, i);
  74720. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74721. if (i === 0) {
  74722. defines += "#define FINAL_DOWN_SAMPLER";
  74723. }
  74724. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74725. this.luminanceDownSamplePostProcesses.push(postProcess);
  74726. }
  74727. // Create callbacks and add effects
  74728. var lastLuminance = this.luminancePostProcess;
  74729. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74730. var downSampleOffsets = new Array(18);
  74731. pp.onApply = function (effect) {
  74732. if (!lastLuminance) {
  74733. return;
  74734. }
  74735. var id = 0;
  74736. for (var x = -1; x < 2; x++) {
  74737. for (var y = -1; y < 2; y++) {
  74738. downSampleOffsets[id] = x / lastLuminance.width;
  74739. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74740. id += 2;
  74741. }
  74742. }
  74743. effect.setArray2("dsOffsets", downSampleOffsets);
  74744. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74745. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74746. lastLuminance = _this.luminancePostProcess;
  74747. }
  74748. else {
  74749. lastLuminance = pp;
  74750. }
  74751. };
  74752. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74753. pp.onAfterRender = function (effect) {
  74754. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74755. 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);
  74756. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74757. };
  74758. }
  74759. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74760. });
  74761. };
  74762. // Create HDR post-process
  74763. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74764. var _this = this;
  74765. 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);
  74766. var outputLiminance = 1;
  74767. var time = 0;
  74768. var lastTime = 0;
  74769. this.hdrPostProcess.onApply = function (effect) {
  74770. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74771. time += scene.getEngine().getDeltaTime();
  74772. if (outputLiminance < 0) {
  74773. outputLiminance = _this._hdrCurrentLuminance;
  74774. }
  74775. else {
  74776. var dt = (lastTime - time) / 1000.0;
  74777. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74778. outputLiminance += _this.hdrDecreaseRate * dt;
  74779. }
  74780. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74781. outputLiminance -= _this.hdrIncreaseRate * dt;
  74782. }
  74783. else {
  74784. outputLiminance = _this._hdrCurrentLuminance;
  74785. }
  74786. }
  74787. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74788. effect.setFloat("averageLuminance", outputLiminance);
  74789. lastTime = time;
  74790. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74791. };
  74792. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74793. };
  74794. // Create lens flare post-process
  74795. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74796. var _this = this;
  74797. 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);
  74798. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74799. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74800. 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);
  74801. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74802. var resolution = new BABYLON.Vector2(0, 0);
  74803. // Lens flare
  74804. this.lensFlarePostProcess.onApply = function (effect) {
  74805. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74806. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74807. effect.setFloat("strength", _this.lensFlareStrength);
  74808. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74809. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74810. // Shift
  74811. resolution.x = _this.lensFlarePostProcess.width;
  74812. resolution.y = _this.lensFlarePostProcess.height;
  74813. effect.setVector2("resolution", resolution);
  74814. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74815. };
  74816. // Compose
  74817. 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);
  74818. 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);
  74819. this.lensFlareComposePostProcess.onApply = function (effect) {
  74820. if (!_this._scene.activeCamera) {
  74821. return;
  74822. }
  74823. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74824. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74825. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74826. // Lens start rotation matrix
  74827. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74828. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74829. 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));
  74830. camRot *= 4.0;
  74831. 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);
  74832. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74833. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74834. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74835. };
  74836. };
  74837. // Create depth-of-field post-process
  74838. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74839. var _this = this;
  74840. 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);
  74841. this.depthOfFieldPostProcess.onApply = function (effect) {
  74842. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74843. effect.setTexture("depthSampler", _this._getDepthTexture());
  74844. effect.setFloat("distance", _this.depthOfFieldDistance);
  74845. };
  74846. // Add to pipeline
  74847. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74848. };
  74849. // Create motion blur post-process
  74850. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74851. var _this = this;
  74852. 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);
  74853. var motionScale = 0;
  74854. var prevViewProjection = BABYLON.Matrix.Identity();
  74855. var invViewProjection = BABYLON.Matrix.Identity();
  74856. var viewProjection = BABYLON.Matrix.Identity();
  74857. var screenSize = BABYLON.Vector2.Zero();
  74858. this.motionBlurPostProcess.onApply = function (effect) {
  74859. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74860. viewProjection.invertToRef(invViewProjection);
  74861. effect.setMatrix("inverseViewProjection", invViewProjection);
  74862. effect.setMatrix("prevViewProjection", prevViewProjection);
  74863. prevViewProjection = viewProjection;
  74864. screenSize.x = _this.motionBlurPostProcess.width;
  74865. screenSize.y = _this.motionBlurPostProcess.height;
  74866. effect.setVector2("screenSize", screenSize);
  74867. motionScale = scene.getEngine().getFps() / 60.0;
  74868. effect.setFloat("motionScale", motionScale);
  74869. effect.setFloat("motionStrength", _this.motionStrength);
  74870. effect.setTexture("depthSampler", _this._getDepthTexture());
  74871. };
  74872. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74873. };
  74874. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74875. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74876. var renderer = this._scene.enableGeometryBufferRenderer();
  74877. return renderer.getGBuffer().textures[0];
  74878. }
  74879. return this._scene.enableDepthRenderer().getDepthMap();
  74880. };
  74881. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74882. for (var i = 0; i < this._cameras.length; i++) {
  74883. var camera = this._cameras[i];
  74884. if (this.originalPostProcess) {
  74885. this.originalPostProcess.dispose(camera);
  74886. }
  74887. if (this.downSampleX4PostProcess) {
  74888. this.downSampleX4PostProcess.dispose(camera);
  74889. }
  74890. if (this.brightPassPostProcess) {
  74891. this.brightPassPostProcess.dispose(camera);
  74892. }
  74893. if (this.textureAdderPostProcess) {
  74894. this.textureAdderPostProcess.dispose(camera);
  74895. }
  74896. if (this.textureAdderFinalPostProcess) {
  74897. this.textureAdderFinalPostProcess.dispose(camera);
  74898. }
  74899. if (this.volumetricLightPostProcess) {
  74900. this.volumetricLightPostProcess.dispose(camera);
  74901. }
  74902. if (this.volumetricLightSmoothXPostProcess) {
  74903. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74904. }
  74905. if (this.volumetricLightSmoothYPostProcess) {
  74906. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74907. }
  74908. if (this.volumetricLightMergePostProces) {
  74909. this.volumetricLightMergePostProces.dispose(camera);
  74910. }
  74911. if (this.volumetricLightFinalPostProcess) {
  74912. this.volumetricLightFinalPostProcess.dispose(camera);
  74913. }
  74914. if (this.lensFlarePostProcess) {
  74915. this.lensFlarePostProcess.dispose(camera);
  74916. }
  74917. if (this.lensFlareComposePostProcess) {
  74918. this.lensFlareComposePostProcess.dispose(camera);
  74919. }
  74920. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74921. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74922. }
  74923. if (this.luminancePostProcess) {
  74924. this.luminancePostProcess.dispose(camera);
  74925. }
  74926. if (this.hdrPostProcess) {
  74927. this.hdrPostProcess.dispose(camera);
  74928. }
  74929. if (this.hdrFinalPostProcess) {
  74930. this.hdrFinalPostProcess.dispose(camera);
  74931. }
  74932. if (this.depthOfFieldPostProcess) {
  74933. this.depthOfFieldPostProcess.dispose(camera);
  74934. }
  74935. if (this.motionBlurPostProcess) {
  74936. this.motionBlurPostProcess.dispose(camera);
  74937. }
  74938. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74939. this.blurHPostProcesses[j].dispose(camera);
  74940. }
  74941. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74942. this.blurVPostProcesses[j].dispose(camera);
  74943. }
  74944. }
  74945. this.originalPostProcess = null;
  74946. this.downSampleX4PostProcess = null;
  74947. this.brightPassPostProcess = null;
  74948. this.textureAdderPostProcess = null;
  74949. this.textureAdderFinalPostProcess = null;
  74950. this.volumetricLightPostProcess = null;
  74951. this.volumetricLightSmoothXPostProcess = null;
  74952. this.volumetricLightSmoothYPostProcess = null;
  74953. this.volumetricLightMergePostProces = null;
  74954. this.volumetricLightFinalPostProcess = null;
  74955. this.lensFlarePostProcess = null;
  74956. this.lensFlareComposePostProcess = null;
  74957. this.luminancePostProcess = null;
  74958. this.hdrPostProcess = null;
  74959. this.hdrFinalPostProcess = null;
  74960. this.depthOfFieldPostProcess = null;
  74961. this.motionBlurPostProcess = null;
  74962. this.luminanceDownSamplePostProcesses = [];
  74963. this.blurHPostProcesses = [];
  74964. this.blurVPostProcesses = [];
  74965. };
  74966. /**
  74967. * Dispose of the pipeline and stop all post processes
  74968. */
  74969. StandardRenderingPipeline.prototype.dispose = function () {
  74970. this._disposePostProcesses();
  74971. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74972. _super.prototype.dispose.call(this);
  74973. };
  74974. /**
  74975. * Serialize the rendering pipeline (Used when exporting)
  74976. * @returns the serialized object
  74977. */
  74978. StandardRenderingPipeline.prototype.serialize = function () {
  74979. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74980. if (this.sourceLight) {
  74981. serializationObject.sourceLightId = this.sourceLight.id;
  74982. }
  74983. serializationObject.customType = "StandardRenderingPipeline";
  74984. return serializationObject;
  74985. };
  74986. /**
  74987. * Parse the serialized pipeline
  74988. * @param source Source pipeline.
  74989. * @param scene The scene to load the pipeline to.
  74990. * @param rootUrl The URL of the serialized pipeline.
  74991. * @returns An instantiated pipeline from the serialized object.
  74992. */
  74993. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74994. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74995. if (source.sourceLightId) {
  74996. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74997. }
  74998. return p;
  74999. };
  75000. // Luminance steps
  75001. StandardRenderingPipeline.LuminanceSteps = 6;
  75002. __decorate([
  75003. BABYLON.serialize()
  75004. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75005. __decorate([
  75006. BABYLON.serialize()
  75007. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75008. __decorate([
  75009. BABYLON.serialize()
  75010. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75011. __decorate([
  75012. BABYLON.serialize()
  75013. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75014. __decorate([
  75015. BABYLON.serializeAsTexture("lensTexture")
  75016. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75017. __decorate([
  75018. BABYLON.serialize()
  75019. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75020. __decorate([
  75021. BABYLON.serialize()
  75022. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75023. __decorate([
  75024. BABYLON.serialize()
  75025. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75026. __decorate([
  75027. BABYLON.serialize()
  75028. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75029. __decorate([
  75030. BABYLON.serialize()
  75031. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75032. __decorate([
  75033. BABYLON.serialize()
  75034. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75035. __decorate([
  75036. BABYLON.serializeAsTexture("lensColorTexture")
  75037. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75038. __decorate([
  75039. BABYLON.serialize()
  75040. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75041. __decorate([
  75042. BABYLON.serialize()
  75043. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75044. __decorate([
  75045. BABYLON.serialize()
  75046. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75047. __decorate([
  75048. BABYLON.serialize()
  75049. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75050. __decorate([
  75051. BABYLON.serializeAsTexture("lensStarTexture")
  75052. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75053. __decorate([
  75054. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75055. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75056. __decorate([
  75057. BABYLON.serialize()
  75058. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75059. __decorate([
  75060. BABYLON.serialize()
  75061. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75062. __decorate([
  75063. BABYLON.serialize()
  75064. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75065. __decorate([
  75066. BABYLON.serialize()
  75067. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75068. __decorate([
  75069. BABYLON.serialize()
  75070. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75071. __decorate([
  75072. BABYLON.serialize()
  75073. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75074. __decorate([
  75075. BABYLON.serialize()
  75076. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75077. __decorate([
  75078. BABYLON.serialize()
  75079. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75080. __decorate([
  75081. BABYLON.serialize()
  75082. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75083. __decorate([
  75084. BABYLON.serialize()
  75085. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75086. __decorate([
  75087. BABYLON.serialize()
  75088. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75089. __decorate([
  75090. BABYLON.serialize()
  75091. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75092. return StandardRenderingPipeline;
  75093. }(BABYLON.PostProcessRenderPipeline));
  75094. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75095. })(BABYLON || (BABYLON = {}));
  75096. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75097. var BABYLON;
  75098. (function (BABYLON) {
  75099. var FxaaPostProcess = /** @class */ (function (_super) {
  75100. __extends(FxaaPostProcess, _super);
  75101. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75102. if (camera === void 0) { camera = null; }
  75103. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75104. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75105. var defines = _this._getDefines();
  75106. _this.updateEffect(defines);
  75107. _this.onApplyObservable.add(function (effect) {
  75108. var texelSize = _this.texelSize;
  75109. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75110. });
  75111. return _this;
  75112. }
  75113. FxaaPostProcess.prototype._getDefines = function () {
  75114. var engine = this.getEngine();
  75115. if (!engine) {
  75116. return null;
  75117. }
  75118. var glInfo = engine.getGlInfo();
  75119. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75120. return "#define MALI 1\n";
  75121. }
  75122. return null;
  75123. };
  75124. return FxaaPostProcess;
  75125. }(BABYLON.PostProcess));
  75126. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75127. })(BABYLON || (BABYLON = {}));
  75128. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75129. var BABYLON;
  75130. (function (BABYLON) {
  75131. /**
  75132. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75133. */
  75134. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75135. __extends(ChromaticAberrationPostProcess, _super);
  75136. /**
  75137. * Creates a new instance ChromaticAberrationPostProcess
  75138. * @param name The name of the effect.
  75139. * @param screenWidth The width of the screen to apply the effect on.
  75140. * @param screenHeight The height of the screen to apply the effect on.
  75141. * @param options The required width/height ratio to downsize to before computing the render pass.
  75142. * @param camera The camera to apply the render pass to.
  75143. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75144. * @param engine The engine which the post process will be applied. (default: current engine)
  75145. * @param reusable If the post process can be reused on the same frame. (default: false)
  75146. * @param textureType Type of textures used when performing the post process. (default: 0)
  75147. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75148. */
  75149. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75150. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75151. if (blockCompilation === void 0) { blockCompilation = false; }
  75152. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75153. /**
  75154. * The amount of seperation of rgb channels (default: 30)
  75155. */
  75156. _this.aberrationAmount = 30;
  75157. /**
  75158. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75159. */
  75160. _this.radialIntensity = 0;
  75161. /**
  75162. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  75163. */
  75164. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75165. /**
  75166. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  75167. */
  75168. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75169. _this.onApplyObservable.add(function (effect) {
  75170. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75171. effect.setFloat('screen_width', screenWidth);
  75172. effect.setFloat('screen_height', screenHeight);
  75173. effect.setFloat('radialIntensity', _this.radialIntensity);
  75174. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75175. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75176. });
  75177. return _this;
  75178. }
  75179. return ChromaticAberrationPostProcess;
  75180. }(BABYLON.PostProcess));
  75181. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75182. })(BABYLON || (BABYLON = {}));
  75183. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75184. var BABYLON;
  75185. (function (BABYLON) {
  75186. /**
  75187. * The GrainPostProcess adds noise to the image at mid luminance levels
  75188. */
  75189. var GrainPostProcess = /** @class */ (function (_super) {
  75190. __extends(GrainPostProcess, _super);
  75191. /**
  75192. * Creates a new instance of @see GrainPostProcess
  75193. * @param name The name of the effect.
  75194. * @param options The required width/height ratio to downsize to before computing the render pass.
  75195. * @param camera The camera to apply the render pass to.
  75196. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75197. * @param engine The engine which the post process will be applied. (default: current engine)
  75198. * @param reusable If the post process can be reused on the same frame. (default: false)
  75199. * @param textureType Type of textures used when performing the post process. (default: 0)
  75200. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75201. */
  75202. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75203. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75204. if (blockCompilation === void 0) { blockCompilation = false; }
  75205. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75206. /**
  75207. * The intensity of the grain added (default: 30)
  75208. */
  75209. _this.intensity = 30;
  75210. /**
  75211. * If the grain should be randomized on every frame
  75212. */
  75213. _this.animated = false;
  75214. _this.onApplyObservable.add(function (effect) {
  75215. effect.setFloat('intensity', _this.intensity);
  75216. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75217. });
  75218. return _this;
  75219. }
  75220. return GrainPostProcess;
  75221. }(BABYLON.PostProcess));
  75222. BABYLON.GrainPostProcess = GrainPostProcess;
  75223. })(BABYLON || (BABYLON = {}));
  75224. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75225. var BABYLON;
  75226. (function (BABYLON) {
  75227. /**
  75228. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75229. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75230. */
  75231. var SharpenPostProcess = /** @class */ (function (_super) {
  75232. __extends(SharpenPostProcess, _super);
  75233. /**
  75234. * Creates a new instance ConvolutionPostProcess
  75235. * @param name The name of the effect.
  75236. * @param options The required width/height ratio to downsize to before computing the render pass.
  75237. * @param camera The camera to apply the render pass to.
  75238. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75239. * @param engine The engine which the post process will be applied. (default: current engine)
  75240. * @param reusable If the post process can be reused on the same frame. (default: false)
  75241. * @param textureType Type of textures used when performing the post process. (default: 0)
  75242. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75243. */
  75244. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75245. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75246. if (blockCompilation === void 0) { blockCompilation = false; }
  75247. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75248. /**
  75249. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75250. */
  75251. _this.colorAmount = 1.0;
  75252. /**
  75253. * How much sharpness should be applied (default: 0.3)
  75254. */
  75255. _this.edgeAmount = 0.3;
  75256. _this.onApply = function (effect) {
  75257. effect.setFloat2("screenSize", _this.width, _this.height);
  75258. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75259. };
  75260. return _this;
  75261. }
  75262. return SharpenPostProcess;
  75263. }(BABYLON.PostProcess));
  75264. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75265. })(BABYLON || (BABYLON = {}));
  75266. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75267. var BABYLON;
  75268. (function (BABYLON) {
  75269. /**
  75270. * The Blur Post Process which blurs an image based on a kernel and direction.
  75271. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75272. */
  75273. var BlurPostProcess = /** @class */ (function (_super) {
  75274. __extends(BlurPostProcess, _super);
  75275. /**
  75276. * Creates a new instance BlurPostProcess
  75277. * @param name The name of the effect.
  75278. * @param direction The direction in which to blur the image.
  75279. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  75280. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75281. * @param camera The camera to apply the render pass to.
  75282. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75283. * @param engine The engine which the post process will be applied. (default: current engine)
  75284. * @param reusable If the post process can be reused on the same frame. (default: false)
  75285. * @param textureType Type of textures used when performing the post process. (default: 0)
  75286. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75287. */
  75288. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75289. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75290. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75291. if (defines === void 0) { defines = ""; }
  75292. if (blockCompilation === void 0) { blockCompilation = false; }
  75293. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  75294. _this.direction = direction;
  75295. _this.blockCompilation = blockCompilation;
  75296. _this._packedFloat = false;
  75297. _this._staticDefines = "";
  75298. _this._staticDefines = defines;
  75299. _this.onApplyObservable.add(function (effect) {
  75300. if (_this._outputTexture) {
  75301. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75302. }
  75303. else {
  75304. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75305. }
  75306. });
  75307. _this.kernel = kernel;
  75308. return _this;
  75309. }
  75310. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75311. /**
  75312. * Gets the length in pixels of the blur sample region
  75313. */
  75314. get: function () {
  75315. return this._idealKernel;
  75316. },
  75317. /**
  75318. * Sets the length in pixels of the blur sample region
  75319. */
  75320. set: function (v) {
  75321. if (this._idealKernel === v) {
  75322. return;
  75323. }
  75324. v = Math.max(v, 1);
  75325. this._idealKernel = v;
  75326. this._kernel = this._nearestBestKernel(v);
  75327. if (!this.blockCompilation) {
  75328. this._updateParameters();
  75329. }
  75330. },
  75331. enumerable: true,
  75332. configurable: true
  75333. });
  75334. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75335. /**
  75336. * Gets wether or not the blur is unpacking/repacking floats
  75337. */
  75338. get: function () {
  75339. return this._packedFloat;
  75340. },
  75341. /**
  75342. * Sets wether or not the blur needs to unpack/repack floats
  75343. */
  75344. set: function (v) {
  75345. if (this._packedFloat === v) {
  75346. return;
  75347. }
  75348. this._packedFloat = v;
  75349. if (!this.blockCompilation) {
  75350. this._updateParameters();
  75351. }
  75352. },
  75353. enumerable: true,
  75354. configurable: true
  75355. });
  75356. /**
  75357. * Updates the effect with the current post process compile time values and recompiles the shader.
  75358. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75359. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75360. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75361. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  75362. * @param onCompiled Called when the shader has been compiled.
  75363. * @param onError Called if there is an error when compiling a shader.
  75364. */
  75365. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75366. if (defines === void 0) { defines = null; }
  75367. if (uniforms === void 0) { uniforms = null; }
  75368. if (samplers === void 0) { samplers = null; }
  75369. this._updateParameters(onCompiled, onError);
  75370. };
  75371. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75372. // Generate sampling offsets and weights
  75373. var N = this._kernel;
  75374. var centerIndex = (N - 1) / 2;
  75375. // Generate Gaussian sampling weights over kernel
  75376. var offsets = [];
  75377. var weights = [];
  75378. var totalWeight = 0;
  75379. for (var i = 0; i < N; i++) {
  75380. var u = i / (N - 1);
  75381. var w = this._gaussianWeight(u * 2.0 - 1);
  75382. offsets[i] = (i - centerIndex);
  75383. weights[i] = w;
  75384. totalWeight += w;
  75385. }
  75386. // Normalize weights
  75387. for (var i = 0; i < weights.length; i++) {
  75388. weights[i] /= totalWeight;
  75389. }
  75390. // Optimize: combine samples to take advantage of hardware linear sampling
  75391. // Walk from left to center, combining pairs (symmetrically)
  75392. var linearSamplingWeights = [];
  75393. var linearSamplingOffsets = [];
  75394. var linearSamplingMap = [];
  75395. for (var i = 0; i <= centerIndex; i += 2) {
  75396. var j = Math.min(i + 1, Math.floor(centerIndex));
  75397. var singleCenterSample = i === j;
  75398. if (singleCenterSample) {
  75399. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75400. }
  75401. else {
  75402. var sharedCell = j === centerIndex;
  75403. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75404. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75405. if (offsetLinear === 0) {
  75406. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75407. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75408. }
  75409. else {
  75410. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75411. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75412. }
  75413. }
  75414. }
  75415. for (var i = 0; i < linearSamplingMap.length; i++) {
  75416. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75417. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75418. }
  75419. // Replace with optimized
  75420. offsets = linearSamplingOffsets;
  75421. weights = linearSamplingWeights;
  75422. // Generate shaders
  75423. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75424. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75425. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75426. var defines = "";
  75427. defines += this._staticDefines;
  75428. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75429. if (this._staticDefines.indexOf("DOF") != -1) {
  75430. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75431. varyingCount--;
  75432. }
  75433. for (var i = 0; i < varyingCount; i++) {
  75434. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75435. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75436. }
  75437. var depCount = 0;
  75438. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75439. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75440. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75441. depCount++;
  75442. }
  75443. if (this.packedFloat) {
  75444. defines += "#define PACKEDFLOAT 1";
  75445. }
  75446. this.blockCompilation = false;
  75447. _super.prototype.updateEffect.call(this, defines, null, null, {
  75448. varyingCount: varyingCount,
  75449. depCount: depCount
  75450. }, onCompiled, onError);
  75451. };
  75452. /**
  75453. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75454. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75455. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75456. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75457. * The gaps between physical kernels are compensated for in the weighting of the samples
  75458. * @param idealKernel Ideal blur kernel.
  75459. * @return Nearest best kernel.
  75460. */
  75461. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75462. var v = Math.round(idealKernel);
  75463. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75464. var k = _a[_i];
  75465. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75466. return Math.max(k, 3);
  75467. }
  75468. }
  75469. return Math.max(v, 3);
  75470. };
  75471. /**
  75472. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75473. * @param x The point on the Gaussian distribution to sample.
  75474. * @return the value of the Gaussian function at x.
  75475. */
  75476. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75477. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75478. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75479. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75480. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75481. // truncated at around 1.3% of peak strength.
  75482. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75483. var sigma = (1 / 3);
  75484. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75485. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75486. var weight = (1.0 / denominator) * Math.exp(exponent);
  75487. return weight;
  75488. };
  75489. /**
  75490. * Generates a string that can be used as a floating point number in GLSL.
  75491. * @param x Value to print.
  75492. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75493. * @return GLSL float string.
  75494. */
  75495. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75496. if (decimalFigures === void 0) { decimalFigures = 8; }
  75497. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75498. };
  75499. return BlurPostProcess;
  75500. }(BABYLON.PostProcess));
  75501. BABYLON.BlurPostProcess = BlurPostProcess;
  75502. })(BABYLON || (BABYLON = {}));
  75503. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75504. var BABYLON;
  75505. (function (BABYLON) {
  75506. /**
  75507. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75508. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75509. * based on samples that have a large difference in distance than the center pixel.
  75510. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75511. */
  75512. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75513. __extends(DepthOfFieldBlurPostProcess, _super);
  75514. /**
  75515. * Creates a new instance CircleOfConfusionPostProcess
  75516. * @param name The name of the effect.
  75517. * @param scene The scene the effect belongs to.
  75518. * @param direction The direction the blur should be applied.
  75519. * @param kernel The size of the kernel used to blur.
  75520. * @param options The required width/height ratio to downsize to before computing the render pass.
  75521. * @param camera The camera to apply the render pass to.
  75522. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75523. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75524. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75525. * @param engine The engine which the post process will be applied. (default: current engine)
  75526. * @param reusable If the post process can be reused on the same frame. (default: false)
  75527. * @param textureType Type of textures used when performing the post process. (default: 0)
  75528. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75529. */
  75530. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75531. if (imageToBlur === void 0) { imageToBlur = null; }
  75532. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75533. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75534. if (blockCompilation === void 0) { blockCompilation = false; }
  75535. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  75536. _this.direction = direction;
  75537. _this.onApplyObservable.add(function (effect) {
  75538. if (imageToBlur != null) {
  75539. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75540. }
  75541. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75542. if (scene.activeCamera) {
  75543. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75544. }
  75545. });
  75546. return _this;
  75547. }
  75548. return DepthOfFieldBlurPostProcess;
  75549. }(BABYLON.BlurPostProcess));
  75550. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75551. })(BABYLON || (BABYLON = {}));
  75552. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75553. var BABYLON;
  75554. (function (BABYLON) {
  75555. /**
  75556. * Options to be set when merging outputs from the default pipeline.
  75557. */
  75558. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75559. function DepthOfFieldMergePostProcessOptions() {
  75560. }
  75561. return DepthOfFieldMergePostProcessOptions;
  75562. }());
  75563. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75564. /**
  75565. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75566. */
  75567. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75568. __extends(DepthOfFieldMergePostProcess, _super);
  75569. /**
  75570. * Creates a new instance of DepthOfFieldMergePostProcess
  75571. * @param name The name of the effect.
  75572. * @param originalFromInput Post process which's input will be used for the merge.
  75573. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75574. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75575. * @param options The required width/height ratio to downsize to before computing the render pass.
  75576. * @param camera The camera to apply the render pass to.
  75577. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75578. * @param engine The engine which the post process will be applied. (default: current engine)
  75579. * @param reusable If the post process can be reused on the same frame. (default: false)
  75580. * @param textureType Type of textures used when performing the post process. (default: 0)
  75581. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75582. */
  75583. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75584. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75585. if (blockCompilation === void 0) { blockCompilation = false; }
  75586. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75587. _this.blurSteps = blurSteps;
  75588. _this.onApplyObservable.add(function (effect) {
  75589. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75590. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75591. blurSteps.forEach(function (step, index) {
  75592. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75593. });
  75594. });
  75595. if (!blockCompilation) {
  75596. _this.updateEffect();
  75597. }
  75598. return _this;
  75599. }
  75600. /**
  75601. * Updates the effect with the current post process compile time values and recompiles the shader.
  75602. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75603. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75604. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75605. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  75606. * @param onCompiled Called when the shader has been compiled.
  75607. * @param onError Called if there is an error when compiling a shader.
  75608. */
  75609. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75610. if (defines === void 0) { defines = null; }
  75611. if (uniforms === void 0) { uniforms = null; }
  75612. if (samplers === void 0) { samplers = null; }
  75613. if (!defines) {
  75614. defines = "";
  75615. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75616. }
  75617. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75618. };
  75619. return DepthOfFieldMergePostProcess;
  75620. }(BABYLON.PostProcess));
  75621. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75622. })(BABYLON || (BABYLON = {}));
  75623. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75624. var BABYLON;
  75625. (function (BABYLON) {
  75626. /**
  75627. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75628. */
  75629. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75630. __extends(CircleOfConfusionPostProcess, _super);
  75631. /**
  75632. * Creates a new instance CircleOfConfusionPostProcess
  75633. * @param name The name of the effect.
  75634. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  75635. * @param options The required width/height ratio to downsize to before computing the render pass.
  75636. * @param camera The camera to apply the render pass to.
  75637. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75638. * @param engine The engine which the post process will be applied. (default: current engine)
  75639. * @param reusable If the post process can be reused on the same frame. (default: false)
  75640. * @param textureType Type of textures used when performing the post process. (default: 0)
  75641. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75642. */
  75643. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75644. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75645. if (blockCompilation === void 0) { blockCompilation = false; }
  75646. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75647. /**
  75648. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  75649. */
  75650. _this.lensSize = 50;
  75651. /**
  75652. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75653. */
  75654. _this.fStop = 1.4;
  75655. /**
  75656. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75657. */
  75658. _this.focusDistance = 2000;
  75659. /**
  75660. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75661. */
  75662. _this.focalLength = 50;
  75663. _this._depthTexture = null;
  75664. _this._depthTexture = depthTexture;
  75665. _this.onApplyObservable.add(function (effect) {
  75666. if (!_this._depthTexture) {
  75667. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75668. return;
  75669. }
  75670. effect.setTexture("depthSampler", _this._depthTexture);
  75671. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75672. var aperture = _this.lensSize / _this.fStop;
  75673. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75674. effect.setFloat('focusDistance', _this.focusDistance);
  75675. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75676. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75677. });
  75678. return _this;
  75679. }
  75680. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75681. /**
  75682. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  75683. */
  75684. set: function (value) {
  75685. this._depthTexture = value;
  75686. },
  75687. enumerable: true,
  75688. configurable: true
  75689. });
  75690. return CircleOfConfusionPostProcess;
  75691. }(BABYLON.PostProcess));
  75692. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75693. })(BABYLON || (BABYLON = {}));
  75694. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75695. var BABYLON;
  75696. (function (BABYLON) {
  75697. /**
  75698. * Specifies the level of max blur that should be applied when using the depth of field effect
  75699. */
  75700. var DepthOfFieldEffectBlurLevel;
  75701. (function (DepthOfFieldEffectBlurLevel) {
  75702. /**
  75703. * Subtle blur
  75704. */
  75705. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75706. /**
  75707. * Medium blur
  75708. */
  75709. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75710. /**
  75711. * Large blur
  75712. */
  75713. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75714. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75715. ;
  75716. /**
  75717. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75718. */
  75719. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75720. __extends(DepthOfFieldEffect, _super);
  75721. /**
  75722. * Creates a new instance DepthOfFieldEffect
  75723. * @param scene The scene the effect belongs to.
  75724. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  75725. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75726. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75727. */
  75728. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75729. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75730. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75731. if (blockCompilation === void 0) { blockCompilation = false; }
  75732. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75733. return _this._effects;
  75734. }, true) || this;
  75735. /**
  75736. * Internal post processes in depth of field effect
  75737. */
  75738. _this._effects = [];
  75739. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75740. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75741. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  75742. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75743. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75744. _this._depthOfFieldBlurY = [];
  75745. _this._depthOfFieldBlurX = [];
  75746. var blurCount = 1;
  75747. var kernelSize = 15;
  75748. switch (blurLevel) {
  75749. case DepthOfFieldEffectBlurLevel.High: {
  75750. blurCount = 3;
  75751. kernelSize = 51;
  75752. break;
  75753. }
  75754. case DepthOfFieldEffectBlurLevel.Medium: {
  75755. blurCount = 2;
  75756. kernelSize = 31;
  75757. break;
  75758. }
  75759. default: {
  75760. kernelSize = 15;
  75761. blurCount = 1;
  75762. break;
  75763. }
  75764. }
  75765. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75766. var ratio = 1.0;
  75767. for (var i = 0; i < blurCount; i++) {
  75768. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75769. blurY.autoClear = false;
  75770. ratio = 0.75 / Math.pow(2, i);
  75771. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75772. blurX.autoClear = false;
  75773. _this._depthOfFieldBlurY.push(blurY);
  75774. _this._depthOfFieldBlurX.push(blurX);
  75775. }
  75776. // Set all post processes on the effect.
  75777. _this._effects = [_this._circleOfConfusion];
  75778. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75779. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75780. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75781. }
  75782. // Merge blurred images with original image based on circleOfConfusion
  75783. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75784. _this._dofMerge.autoClear = false;
  75785. _this._effects.push(_this._dofMerge);
  75786. return _this;
  75787. }
  75788. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75789. get: function () {
  75790. return this._circleOfConfusion.focalLength;
  75791. },
  75792. /**
  75793. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75794. */
  75795. set: function (value) {
  75796. this._circleOfConfusion.focalLength = value;
  75797. },
  75798. enumerable: true,
  75799. configurable: true
  75800. });
  75801. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75802. get: function () {
  75803. return this._circleOfConfusion.fStop;
  75804. },
  75805. /**
  75806. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75807. */
  75808. set: function (value) {
  75809. this._circleOfConfusion.fStop = value;
  75810. },
  75811. enumerable: true,
  75812. configurable: true
  75813. });
  75814. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75815. get: function () {
  75816. return this._circleOfConfusion.focusDistance;
  75817. },
  75818. /**
  75819. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75820. */
  75821. set: function (value) {
  75822. this._circleOfConfusion.focusDistance = value;
  75823. },
  75824. enumerable: true,
  75825. configurable: true
  75826. });
  75827. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75828. get: function () {
  75829. return this._circleOfConfusion.lensSize;
  75830. },
  75831. /**
  75832. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  75833. */
  75834. set: function (value) {
  75835. this._circleOfConfusion.lensSize = value;
  75836. },
  75837. enumerable: true,
  75838. configurable: true
  75839. });
  75840. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75841. /**
  75842. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  75843. */
  75844. set: function (value) {
  75845. this._circleOfConfusion.depthTexture = value;
  75846. },
  75847. enumerable: true,
  75848. configurable: true
  75849. });
  75850. /**
  75851. * Disposes each of the internal effects for a given camera.
  75852. * @param camera The camera to dispose the effect on.
  75853. */
  75854. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75855. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75856. this._effects[effectIndex].dispose(camera);
  75857. }
  75858. };
  75859. /**
  75860. * Internal
  75861. */
  75862. DepthOfFieldEffect.prototype._updateEffects = function () {
  75863. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75864. this._effects[effectIndex].updateEffect();
  75865. }
  75866. };
  75867. /**
  75868. * Internal
  75869. * @returns if all the contained post processes are ready.
  75870. */
  75871. DepthOfFieldEffect.prototype._isReady = function () {
  75872. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75873. if (!this._effects[effectIndex].isReady()) {
  75874. return false;
  75875. }
  75876. }
  75877. return true;
  75878. };
  75879. return DepthOfFieldEffect;
  75880. }(BABYLON.PostProcessRenderEffect));
  75881. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75882. })(BABYLON || (BABYLON = {}));
  75883. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75884. var BABYLON;
  75885. (function (BABYLON) {
  75886. /**
  75887. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75888. */
  75889. var BloomMergePostProcess = /** @class */ (function (_super) {
  75890. __extends(BloomMergePostProcess, _super);
  75891. /**
  75892. * Creates a new instance of @see BloomMergePostProcess
  75893. * @param name The name of the effect.
  75894. * @param originalFromInput Post process which's input will be used for the merge.
  75895. * @param blurred Blurred highlights post process which's output will be used.
  75896. * @param weight Weight of the bloom to be added to the original input.
  75897. * @param options The required width/height ratio to downsize to before computing the render pass.
  75898. * @param camera The camera to apply the render pass to.
  75899. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75900. * @param engine The engine which the post process will be applied. (default: current engine)
  75901. * @param reusable If the post process can be reused on the same frame. (default: false)
  75902. * @param textureType Type of textures used when performing the post process. (default: 0)
  75903. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75904. */
  75905. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75906. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75907. if (blockCompilation === void 0) { blockCompilation = false; }
  75908. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75909. _this.weight = weight;
  75910. _this.onApplyObservable.add(function (effect) {
  75911. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75912. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75913. effect.setFloat("bloomWeight", _this.weight);
  75914. });
  75915. if (!blockCompilation) {
  75916. _this.updateEffect();
  75917. }
  75918. return _this;
  75919. }
  75920. return BloomMergePostProcess;
  75921. }(BABYLON.PostProcess));
  75922. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75923. })(BABYLON || (BABYLON = {}));
  75924. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75925. var BABYLON;
  75926. (function (BABYLON) {
  75927. /**
  75928. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  75929. */
  75930. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75931. __extends(ExtractHighlightsPostProcess, _super);
  75932. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75933. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75934. if (blockCompilation === void 0) { blockCompilation = false; }
  75935. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75936. /**
  75937. * The luminance threshold, pixels below this value will be set to black.
  75938. */
  75939. _this.threshold = 0.9;
  75940. /**
  75941. * Internal
  75942. */
  75943. _this._exposure = 1;
  75944. /**
  75945. * Post process which has the input texture to be used when performing highlight extraction
  75946. */
  75947. _this._inputPostProcess = null;
  75948. _this.onApplyObservable.add(function (effect) {
  75949. if (_this._inputPostProcess) {
  75950. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75951. }
  75952. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75953. effect.setFloat('exposure', _this._exposure);
  75954. });
  75955. return _this;
  75956. }
  75957. return ExtractHighlightsPostProcess;
  75958. }(BABYLON.PostProcess));
  75959. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75960. })(BABYLON || (BABYLON = {}));
  75961. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75962. var BABYLON;
  75963. (function (BABYLON) {
  75964. /**
  75965. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75966. */
  75967. var BloomEffect = /** @class */ (function (_super) {
  75968. __extends(BloomEffect, _super);
  75969. /**
  75970. * Creates a new instance of @see BloomEffect
  75971. * @param scene The scene the effect belongs to.
  75972. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75973. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75974. * @param bloomWeight The the strength of bloom.
  75975. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75976. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75977. */
  75978. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75979. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75980. if (blockCompilation === void 0) { blockCompilation = false; }
  75981. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75982. return _this._effects;
  75983. }, true) || this;
  75984. _this.bloomScale = bloomScale;
  75985. /**
  75986. * Internal
  75987. */
  75988. _this._effects = [];
  75989. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75990. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75991. _this._blurX.alwaysForcePOT = true;
  75992. _this._blurX.autoClear = false;
  75993. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75994. _this._blurY.alwaysForcePOT = true;
  75995. _this._blurY.autoClear = false;
  75996. _this.kernel = bloomKernel;
  75997. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75998. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75999. _this._merge.autoClear = false;
  76000. _this._effects.push(_this._merge);
  76001. return _this;
  76002. }
  76003. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76004. /**
  76005. * The luminance threshold to find bright areas of the image to bloom.
  76006. */
  76007. get: function () {
  76008. return this._downscale.threshold;
  76009. },
  76010. set: function (value) {
  76011. this._downscale.threshold = value;
  76012. },
  76013. enumerable: true,
  76014. configurable: true
  76015. });
  76016. Object.defineProperty(BloomEffect.prototype, "weight", {
  76017. /**
  76018. * The strength of the bloom.
  76019. */
  76020. get: function () {
  76021. return this._merge.weight;
  76022. },
  76023. set: function (value) {
  76024. this._merge.weight = value;
  76025. },
  76026. enumerable: true,
  76027. configurable: true
  76028. });
  76029. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76030. /**
  76031. * Specifies the size of the bloom blur kernel, relative to the final output size
  76032. */
  76033. get: function () {
  76034. return this._blurX.kernel / this.bloomScale;
  76035. },
  76036. set: function (value) {
  76037. this._blurX.kernel = value * this.bloomScale;
  76038. this._blurY.kernel = value * this.bloomScale;
  76039. },
  76040. enumerable: true,
  76041. configurable: true
  76042. });
  76043. /**
  76044. * Disposes each of the internal effects for a given camera.
  76045. * @param camera The camera to dispose the effect on.
  76046. */
  76047. BloomEffect.prototype.disposeEffects = function (camera) {
  76048. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76049. this._effects[effectIndex].dispose(camera);
  76050. }
  76051. };
  76052. /**
  76053. * Internal
  76054. */
  76055. BloomEffect.prototype._updateEffects = function () {
  76056. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76057. this._effects[effectIndex].updateEffect();
  76058. }
  76059. };
  76060. /**
  76061. * Internal
  76062. * @returns if all the contained post processes are ready.
  76063. */
  76064. BloomEffect.prototype._isReady = function () {
  76065. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76066. if (!this._effects[effectIndex].isReady()) {
  76067. return false;
  76068. }
  76069. }
  76070. return true;
  76071. };
  76072. return BloomEffect;
  76073. }(BABYLON.PostProcessRenderEffect));
  76074. BABYLON.BloomEffect = BloomEffect;
  76075. })(BABYLON || (BABYLON = {}));
  76076. //# sourceMappingURL=babylon.bloomEffect.js.map
  76077. var BABYLON;
  76078. (function (BABYLON) {
  76079. /**
  76080. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76081. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76082. */
  76083. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76084. __extends(DefaultRenderingPipeline, _super);
  76085. /**
  76086. * @constructor
  76087. * @param {string} name - The rendering pipeline name (default: "")
  76088. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76089. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76090. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76091. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76092. */
  76093. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76094. if (name === void 0) { name = ""; }
  76095. if (hdr === void 0) { hdr = true; }
  76096. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76097. if (automaticBuild === void 0) { automaticBuild = true; }
  76098. var _this = _super.call(this, scene.getEngine(), name) || this;
  76099. _this._camerasToBeAttached = [];
  76100. /**
  76101. * ID of the sharpen post process,
  76102. */
  76103. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76104. /**
  76105. * ID of the image processing post process;
  76106. */
  76107. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76108. /**
  76109. * ID of the Fast Approximate Anti-Aliasing post process;
  76110. */
  76111. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76112. /**
  76113. * ID of the chromatic aberration post process,
  76114. */
  76115. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76116. /**
  76117. * ID of the grain post process
  76118. */
  76119. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76120. /**
  76121. * Glow post process which adds a glow to emmisive areas of the image
  76122. */
  76123. _this._glowLayer = null;
  76124. /**
  76125. * Animations which can be used to tweak settings over a period of time
  76126. */
  76127. _this.animations = [];
  76128. _this._imageProcessingConfigurationObserver = null;
  76129. // Values
  76130. _this._sharpenEnabled = false;
  76131. _this._bloomEnabled = false;
  76132. _this._depthOfFieldEnabled = false;
  76133. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76134. _this._fxaaEnabled = false;
  76135. _this._imageProcessingEnabled = true;
  76136. _this._bloomScale = 0.5;
  76137. _this._chromaticAberrationEnabled = false;
  76138. _this._grainEnabled = false;
  76139. _this._buildAllowed = true;
  76140. _this._resizeObserver = null;
  76141. _this._hardwareScaleLevel = 1.0;
  76142. _this._bloomKernel = 64;
  76143. /**
  76144. * Specifies the weight of the bloom in the final rendering
  76145. */
  76146. _this._bloomWeight = 0.15;
  76147. /**
  76148. * Specifies the luma threshold for the area that will be blurred by the bloom
  76149. */
  76150. _this._bloomThreshold = 0.9;
  76151. _this._samples = 1;
  76152. _this._hasCleared = false;
  76153. _this._prevPostProcess = null;
  76154. _this._prevPrevPostProcess = null;
  76155. _this._cameras = cameras || scene.cameras;
  76156. _this._camerasToBeAttached = _this._cameras.slice();
  76157. _this._buildAllowed = automaticBuild;
  76158. // Initialize
  76159. _this._scene = scene;
  76160. var caps = _this._scene.getEngine().getCaps();
  76161. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76162. // Misc
  76163. if (_this._hdr) {
  76164. if (caps.textureHalfFloatRender) {
  76165. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76166. }
  76167. else if (caps.textureFloatRender) {
  76168. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76169. }
  76170. }
  76171. else {
  76172. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76173. }
  76174. // Attach
  76175. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76176. var engine = _this._scene.getEngine();
  76177. // Create post processes before hand so they can be modified before enabled.
  76178. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76179. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76180. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76181. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76182. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76183. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76184. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76185. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76186. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76187. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76188. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76189. _this.bloomKernel = _this.bloomKernel;
  76190. });
  76191. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76192. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76193. });
  76194. _this._buildPipeline();
  76195. return _this;
  76196. }
  76197. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76198. get: function () {
  76199. return this._sharpenEnabled;
  76200. },
  76201. /**
  76202. * Enable or disable the sharpen process from the pipeline
  76203. */
  76204. set: function (enabled) {
  76205. if (this._sharpenEnabled === enabled) {
  76206. return;
  76207. }
  76208. this._sharpenEnabled = enabled;
  76209. this._buildPipeline();
  76210. },
  76211. enumerable: true,
  76212. configurable: true
  76213. });
  76214. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76215. /**
  76216. * Specifies the size of the bloom blur kernel, relative to the final output size
  76217. */
  76218. get: function () {
  76219. return this._bloomKernel;
  76220. },
  76221. set: function (value) {
  76222. this._bloomKernel = value;
  76223. this.bloom.kernel = value / this._hardwareScaleLevel;
  76224. },
  76225. enumerable: true,
  76226. configurable: true
  76227. });
  76228. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76229. get: function () {
  76230. return this._bloomWeight;
  76231. },
  76232. /**
  76233. * The strength of the bloom.
  76234. */
  76235. set: function (value) {
  76236. if (this._bloomWeight === value) {
  76237. return;
  76238. }
  76239. this.bloom.weight = value;
  76240. this._bloomWeight = value;
  76241. },
  76242. enumerable: true,
  76243. configurable: true
  76244. });
  76245. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76246. get: function () {
  76247. return this._bloomThreshold;
  76248. },
  76249. /**
  76250. * The strength of the bloom.
  76251. */
  76252. set: function (value) {
  76253. if (this._bloomThreshold === value) {
  76254. return;
  76255. }
  76256. this.bloom.threshold = value;
  76257. this._bloomThreshold = value;
  76258. },
  76259. enumerable: true,
  76260. configurable: true
  76261. });
  76262. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76263. get: function () {
  76264. return this._bloomScale;
  76265. },
  76266. /**
  76267. * The scale of the bloom, lower value will provide better performance.
  76268. */
  76269. set: function (value) {
  76270. if (this._bloomScale === value) {
  76271. return;
  76272. }
  76273. this._bloomScale = value;
  76274. // recreate bloom and dispose old as this setting is not dynamic
  76275. this._rebuildBloom();
  76276. this._buildPipeline();
  76277. },
  76278. enumerable: true,
  76279. configurable: true
  76280. });
  76281. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76282. get: function () {
  76283. return this._bloomEnabled;
  76284. },
  76285. /**
  76286. * Enable or disable the bloom from the pipeline
  76287. */
  76288. set: function (enabled) {
  76289. if (this._bloomEnabled === enabled) {
  76290. return;
  76291. }
  76292. this._bloomEnabled = enabled;
  76293. this._buildPipeline();
  76294. },
  76295. enumerable: true,
  76296. configurable: true
  76297. });
  76298. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76299. // recreate bloom and dispose old as this setting is not dynamic
  76300. var oldBloom = this.bloom;
  76301. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76302. this.bloom.threshold = oldBloom.threshold;
  76303. for (var i = 0; i < this._cameras.length; i++) {
  76304. oldBloom.disposeEffects(this._cameras[i]);
  76305. }
  76306. };
  76307. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76308. /**
  76309. * If the depth of field is enabled.
  76310. */
  76311. get: function () {
  76312. return this._depthOfFieldEnabled;
  76313. },
  76314. set: function (enabled) {
  76315. if (this._depthOfFieldEnabled === enabled) {
  76316. return;
  76317. }
  76318. this._depthOfFieldEnabled = enabled;
  76319. this._buildPipeline();
  76320. },
  76321. enumerable: true,
  76322. configurable: true
  76323. });
  76324. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76325. /**
  76326. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76327. */
  76328. get: function () {
  76329. return this._depthOfFieldBlurLevel;
  76330. },
  76331. set: function (value) {
  76332. if (this._depthOfFieldBlurLevel === value) {
  76333. return;
  76334. }
  76335. this._depthOfFieldBlurLevel = value;
  76336. // recreate dof and dispose old as this setting is not dynamic
  76337. var oldDof = this.depthOfField;
  76338. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76339. this.depthOfField.focalLength = oldDof.focalLength;
  76340. this.depthOfField.focusDistance = oldDof.focusDistance;
  76341. this.depthOfField.fStop = oldDof.fStop;
  76342. this.depthOfField.lensSize = oldDof.lensSize;
  76343. for (var i = 0; i < this._cameras.length; i++) {
  76344. oldDof.disposeEffects(this._cameras[i]);
  76345. }
  76346. this._buildPipeline();
  76347. },
  76348. enumerable: true,
  76349. configurable: true
  76350. });
  76351. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76352. get: function () {
  76353. return this._fxaaEnabled;
  76354. },
  76355. /**
  76356. * If the anti aliasing is enabled.
  76357. */
  76358. set: function (enabled) {
  76359. if (this._fxaaEnabled === enabled) {
  76360. return;
  76361. }
  76362. this._fxaaEnabled = enabled;
  76363. this._buildPipeline();
  76364. },
  76365. enumerable: true,
  76366. configurable: true
  76367. });
  76368. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76369. get: function () {
  76370. return this._samples;
  76371. },
  76372. /**
  76373. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76374. */
  76375. set: function (sampleCount) {
  76376. if (this._samples === sampleCount) {
  76377. return;
  76378. }
  76379. this._samples = sampleCount;
  76380. this._buildPipeline();
  76381. },
  76382. enumerable: true,
  76383. configurable: true
  76384. });
  76385. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76386. get: function () {
  76387. return this._imageProcessingEnabled;
  76388. },
  76389. /**
  76390. * If image processing is enabled.
  76391. */
  76392. set: function (enabled) {
  76393. if (this._imageProcessingEnabled === enabled) {
  76394. return;
  76395. }
  76396. this._imageProcessingEnabled = enabled;
  76397. this._buildPipeline();
  76398. },
  76399. enumerable: true,
  76400. configurable: true
  76401. });
  76402. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76403. get: function () {
  76404. return this._glowLayer == null;
  76405. },
  76406. /**
  76407. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76408. */
  76409. set: function (enabled) {
  76410. if (enabled && !this._glowLayer) {
  76411. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76412. }
  76413. else if (!enabled && this._glowLayer) {
  76414. this._glowLayer.dispose();
  76415. this._glowLayer = null;
  76416. }
  76417. },
  76418. enumerable: true,
  76419. configurable: true
  76420. });
  76421. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76422. get: function () {
  76423. return this._chromaticAberrationEnabled;
  76424. },
  76425. /**
  76426. * Enable or disable the chromaticAberration process from the pipeline
  76427. */
  76428. set: function (enabled) {
  76429. if (this._chromaticAberrationEnabled === enabled) {
  76430. return;
  76431. }
  76432. this._chromaticAberrationEnabled = enabled;
  76433. this._buildPipeline();
  76434. },
  76435. enumerable: true,
  76436. configurable: true
  76437. });
  76438. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76439. get: function () {
  76440. return this._grainEnabled;
  76441. },
  76442. /**
  76443. * Enable or disable the grain process from the pipeline
  76444. */
  76445. set: function (enabled) {
  76446. if (this._grainEnabled === enabled) {
  76447. return;
  76448. }
  76449. this._grainEnabled = enabled;
  76450. this._buildPipeline();
  76451. },
  76452. enumerable: true,
  76453. configurable: true
  76454. });
  76455. /**
  76456. * Force the compilation of the entire pipeline.
  76457. */
  76458. DefaultRenderingPipeline.prototype.prepare = function () {
  76459. var previousState = this._buildAllowed;
  76460. this._buildAllowed = true;
  76461. this._buildPipeline();
  76462. this._buildAllowed = previousState;
  76463. };
  76464. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76465. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76466. if (this._hasCleared) {
  76467. postProcess.autoClear = false;
  76468. }
  76469. else {
  76470. postProcess.autoClear = true;
  76471. this._scene.autoClear = false;
  76472. this._hasCleared = true;
  76473. }
  76474. if (!skipTextureSharing) {
  76475. if (this._prevPrevPostProcess) {
  76476. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76477. }
  76478. else {
  76479. postProcess.useOwnOutput();
  76480. }
  76481. if (this._prevPostProcess) {
  76482. this._prevPrevPostProcess = this._prevPostProcess;
  76483. }
  76484. this._prevPostProcess = postProcess;
  76485. }
  76486. };
  76487. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76488. var _this = this;
  76489. if (!this._buildAllowed) {
  76490. return;
  76491. }
  76492. this._scene.autoClear = true;
  76493. var engine = this._scene.getEngine();
  76494. this._disposePostProcesses();
  76495. if (this._cameras !== null) {
  76496. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76497. // get back cameras to be used to reattach pipeline
  76498. this._cameras = this._camerasToBeAttached.slice();
  76499. }
  76500. this._reset();
  76501. this._prevPostProcess = null;
  76502. this._prevPrevPostProcess = null;
  76503. this._hasCleared = false;
  76504. if (this.depthOfFieldEnabled) {
  76505. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76506. this.depthOfField.depthTexture = depthTexture;
  76507. if (!this.depthOfField._isReady()) {
  76508. this.depthOfField._updateEffects();
  76509. }
  76510. this.addEffect(this.depthOfField);
  76511. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76512. }
  76513. if (this.bloomEnabled) {
  76514. if (!this.bloom._isReady()) {
  76515. this.bloom._updateEffects();
  76516. }
  76517. this.addEffect(this.bloom);
  76518. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76519. }
  76520. if (this._imageProcessingEnabled) {
  76521. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76522. if (this._hdr) {
  76523. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76524. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76525. }
  76526. else {
  76527. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76528. }
  76529. }
  76530. if (this.sharpenEnabled) {
  76531. if (!this.sharpen.isReady()) {
  76532. this.sharpen.updateEffect();
  76533. }
  76534. this.addEffect(this._sharpenEffect);
  76535. this._setAutoClearAndTextureSharing(this.sharpen);
  76536. }
  76537. if (this.grainEnabled) {
  76538. if (!this.grain.isReady()) {
  76539. this.grain.updateEffect();
  76540. }
  76541. this.addEffect(this._grainEffect);
  76542. this._setAutoClearAndTextureSharing(this.grain);
  76543. }
  76544. if (this.chromaticAberrationEnabled) {
  76545. if (!this.chromaticAberration.isReady()) {
  76546. this.chromaticAberration.updateEffect();
  76547. }
  76548. this.addEffect(this._chromaticAberrationEffect);
  76549. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76550. }
  76551. if (this.fxaaEnabled) {
  76552. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76553. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76554. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76555. }
  76556. if (this._cameras !== null) {
  76557. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76558. }
  76559. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76560. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76561. }
  76562. };
  76563. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76564. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76565. for (var i = 0; i < this._cameras.length; i++) {
  76566. var camera = this._cameras[i];
  76567. if (this.imageProcessing) {
  76568. this.imageProcessing.dispose(camera);
  76569. }
  76570. if (this.fxaa) {
  76571. this.fxaa.dispose(camera);
  76572. }
  76573. // These are created in the constructor and should not be disposed on every pipeline change
  76574. if (disposeNonRecreated) {
  76575. if (this.sharpen) {
  76576. this.sharpen.dispose(camera);
  76577. }
  76578. if (this.depthOfField) {
  76579. this.depthOfField.disposeEffects(camera);
  76580. }
  76581. if (this.bloom) {
  76582. this.bloom.disposeEffects(camera);
  76583. }
  76584. if (this.chromaticAberration) {
  76585. this.chromaticAberration.dispose(camera);
  76586. }
  76587. if (this.grain) {
  76588. this.grain.dispose(camera);
  76589. }
  76590. if (this._glowLayer) {
  76591. this._glowLayer.dispose();
  76592. }
  76593. }
  76594. }
  76595. this.imageProcessing = null;
  76596. this.fxaa = null;
  76597. if (disposeNonRecreated) {
  76598. this.sharpen = null;
  76599. this._sharpenEffect = null;
  76600. this.depthOfField = null;
  76601. this.bloom = null;
  76602. this.chromaticAberration = null;
  76603. this._chromaticAberrationEffect = null;
  76604. this.grain = null;
  76605. this._grainEffect = null;
  76606. this._glowLayer = null;
  76607. }
  76608. };
  76609. /**
  76610. * Adds a camera to the pipeline
  76611. * @param camera the camera to be added
  76612. */
  76613. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  76614. this._camerasToBeAttached.push(camera);
  76615. this._buildPipeline();
  76616. };
  76617. /**
  76618. * Removes a camera from the pipeline
  76619. * @param camera the camera to remove
  76620. */
  76621. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  76622. var index = this._camerasToBeAttached.indexOf(camera);
  76623. this._camerasToBeAttached.splice(index, 1);
  76624. this._buildPipeline();
  76625. };
  76626. /**
  76627. * Dispose of the pipeline and stop all post processes
  76628. */
  76629. DefaultRenderingPipeline.prototype.dispose = function () {
  76630. this._disposePostProcesses(true);
  76631. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76632. this._scene.autoClear = true;
  76633. if (this._resizeObserver) {
  76634. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76635. this._resizeObserver = null;
  76636. }
  76637. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76638. _super.prototype.dispose.call(this);
  76639. };
  76640. /**
  76641. * Serialize the rendering pipeline (Used when exporting)
  76642. * @returns the serialized object
  76643. */
  76644. DefaultRenderingPipeline.prototype.serialize = function () {
  76645. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76646. serializationObject.customType = "DefaultRenderingPipeline";
  76647. return serializationObject;
  76648. };
  76649. /**
  76650. * Parse the serialized pipeline
  76651. * @param source Source pipeline.
  76652. * @param scene The scene to load the pipeline to.
  76653. * @param rootUrl The URL of the serialized pipeline.
  76654. * @returns An instantiated pipeline from the serialized object.
  76655. */
  76656. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76657. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76658. };
  76659. __decorate([
  76660. BABYLON.serialize()
  76661. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76662. __decorate([
  76663. BABYLON.serialize()
  76664. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76665. __decorate([
  76666. BABYLON.serialize()
  76667. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76668. __decorate([
  76669. BABYLON.serialize()
  76670. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76671. __decorate([
  76672. BABYLON.serialize()
  76673. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76674. __decorate([
  76675. BABYLON.serialize()
  76676. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76677. __decorate([
  76678. BABYLON.serialize()
  76679. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76680. __decorate([
  76681. BABYLON.serialize()
  76682. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76683. __decorate([
  76684. BABYLON.serialize()
  76685. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76686. __decorate([
  76687. BABYLON.serialize()
  76688. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76689. __decorate([
  76690. BABYLON.serialize()
  76691. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76692. __decorate([
  76693. BABYLON.serialize()
  76694. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76695. __decorate([
  76696. BABYLON.serialize()
  76697. ], DefaultRenderingPipeline.prototype, "samples", null);
  76698. __decorate([
  76699. BABYLON.serialize()
  76700. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76701. __decorate([
  76702. BABYLON.serialize()
  76703. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76704. __decorate([
  76705. BABYLON.serialize()
  76706. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76707. __decorate([
  76708. BABYLON.serialize()
  76709. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76710. return DefaultRenderingPipeline;
  76711. }(BABYLON.PostProcessRenderPipeline));
  76712. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76713. })(BABYLON || (BABYLON = {}));
  76714. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76715. var BABYLON;
  76716. (function (BABYLON) {
  76717. /**
  76718. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76719. */
  76720. var GeometryBufferRenderer = /** @class */ (function () {
  76721. /**
  76722. * Creates a new G Buffer for the scene
  76723. * @param scene The scene the buffer belongs to
  76724. * @param ratio How big is the buffer related to the main canvas.
  76725. */
  76726. function GeometryBufferRenderer(scene, ratio) {
  76727. if (ratio === void 0) { ratio = 1; }
  76728. this._enablePosition = false;
  76729. this._scene = scene;
  76730. this._ratio = ratio;
  76731. // Render target
  76732. this._createRenderTargets();
  76733. }
  76734. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76735. /**
  76736. * Set the render list (meshes to be rendered) used in the G buffer.
  76737. */
  76738. set: function (meshes) {
  76739. this._multiRenderTarget.renderList = meshes;
  76740. },
  76741. enumerable: true,
  76742. configurable: true
  76743. });
  76744. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76745. /**
  76746. * Gets wether or not G buffer are supported by the running hardware.
  76747. * This requires draw buffer supports
  76748. */
  76749. get: function () {
  76750. return this._multiRenderTarget.isSupported;
  76751. },
  76752. enumerable: true,
  76753. configurable: true
  76754. });
  76755. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76756. /**
  76757. * Gets wether or not position are enabled for the G buffer.
  76758. */
  76759. get: function () {
  76760. return this._enablePosition;
  76761. },
  76762. /**
  76763. * Sets wether or not position are enabled for the G buffer.
  76764. */
  76765. set: function (enable) {
  76766. this._enablePosition = enable;
  76767. this.dispose();
  76768. this._createRenderTargets();
  76769. },
  76770. enumerable: true,
  76771. configurable: true
  76772. });
  76773. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76774. /**
  76775. * Gets the scene associated with the buffer.
  76776. */
  76777. get: function () {
  76778. return this._scene;
  76779. },
  76780. enumerable: true,
  76781. configurable: true
  76782. });
  76783. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76784. /**
  76785. * Gets the ratio used by the buffer during its creation.
  76786. * How big is the buffer related to the main canvas.
  76787. */
  76788. get: function () {
  76789. return this._ratio;
  76790. },
  76791. enumerable: true,
  76792. configurable: true
  76793. });
  76794. /**
  76795. * Checks wether everything is ready to render a submesh to the G buffer.
  76796. * @param subMesh the submesh to check readiness for
  76797. * @param useInstances is the mesh drawn using instance or not
  76798. * @returns true if ready otherwise false
  76799. */
  76800. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76801. var material = subMesh.getMaterial();
  76802. if (material && material.disableDepthWrite) {
  76803. return false;
  76804. }
  76805. var defines = [];
  76806. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76807. var mesh = subMesh.getMesh();
  76808. // Alpha test
  76809. if (material && material.needAlphaTesting()) {
  76810. defines.push("#define ALPHATEST");
  76811. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76812. attribs.push(BABYLON.VertexBuffer.UVKind);
  76813. defines.push("#define UV1");
  76814. }
  76815. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76816. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76817. defines.push("#define UV2");
  76818. }
  76819. }
  76820. // Buffers
  76821. if (this._enablePosition) {
  76822. defines.push("#define POSITION");
  76823. }
  76824. // Bones
  76825. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76826. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76827. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76828. if (mesh.numBoneInfluencers > 4) {
  76829. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76830. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76831. }
  76832. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76833. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76834. }
  76835. else {
  76836. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76837. }
  76838. // Instances
  76839. if (useInstances) {
  76840. defines.push("#define INSTANCES");
  76841. attribs.push("world0");
  76842. attribs.push("world1");
  76843. attribs.push("world2");
  76844. attribs.push("world3");
  76845. }
  76846. // Get correct effect
  76847. var join = defines.join("\n");
  76848. if (this._cachedDefines !== join) {
  76849. this._cachedDefines = join;
  76850. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76851. }
  76852. return this._effect.isReady();
  76853. };
  76854. /**
  76855. * Gets the current underlying G Buffer.
  76856. * @returns the buffer
  76857. */
  76858. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76859. return this._multiRenderTarget;
  76860. };
  76861. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76862. /**
  76863. * Gets the number of samples used to render the buffer (anti aliasing).
  76864. */
  76865. get: function () {
  76866. return this._multiRenderTarget.samples;
  76867. },
  76868. /**
  76869. * Sets the number of samples used to render the buffer (anti aliasing).
  76870. */
  76871. set: function (value) {
  76872. this._multiRenderTarget.samples = value;
  76873. },
  76874. enumerable: true,
  76875. configurable: true
  76876. });
  76877. /**
  76878. * Disposes the renderer and frees up associated resources.
  76879. */
  76880. GeometryBufferRenderer.prototype.dispose = function () {
  76881. this.getGBuffer().dispose();
  76882. };
  76883. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76884. var _this = this;
  76885. var engine = this._scene.getEngine();
  76886. var count = this._enablePosition ? 3 : 2;
  76887. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  76888. if (!this.isSupported) {
  76889. return;
  76890. }
  76891. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76892. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76893. this._multiRenderTarget.refreshRate = 1;
  76894. this._multiRenderTarget.renderParticles = false;
  76895. this._multiRenderTarget.renderList = null;
  76896. // set default depth value to 1.0 (far away)
  76897. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76898. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76899. });
  76900. // Custom render function
  76901. var renderSubMesh = function (subMesh) {
  76902. var mesh = subMesh.getRenderingMesh();
  76903. var scene = _this._scene;
  76904. var engine = scene.getEngine();
  76905. var material = subMesh.getMaterial();
  76906. if (!material) {
  76907. return;
  76908. }
  76909. // Culling
  76910. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76911. // Managing instances
  76912. var batch = mesh._getInstancesRenderList(subMesh._id);
  76913. if (batch.mustReturn) {
  76914. return;
  76915. }
  76916. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76917. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76918. engine.enableEffect(_this._effect);
  76919. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76920. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76921. _this._effect.setMatrix("view", scene.getViewMatrix());
  76922. // Alpha test
  76923. if (material && material.needAlphaTesting()) {
  76924. var alphaTexture = material.getAlphaTestTexture();
  76925. if (alphaTexture) {
  76926. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76927. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76928. }
  76929. }
  76930. // Bones
  76931. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76932. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76933. }
  76934. // Draw
  76935. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76936. }
  76937. };
  76938. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76939. var index;
  76940. if (depthOnlySubMeshes.length) {
  76941. engine.setColorWrite(false);
  76942. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76943. renderSubMesh(depthOnlySubMeshes.data[index]);
  76944. }
  76945. engine.setColorWrite(true);
  76946. }
  76947. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76948. renderSubMesh(opaqueSubMeshes.data[index]);
  76949. }
  76950. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76951. renderSubMesh(alphaTestSubMeshes.data[index]);
  76952. }
  76953. };
  76954. };
  76955. return GeometryBufferRenderer;
  76956. }());
  76957. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76958. })(BABYLON || (BABYLON = {}));
  76959. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76960. var BABYLON;
  76961. (function (BABYLON) {
  76962. /**
  76963. * This groups together the common properties used for image processing either in direct forward pass
  76964. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76965. * or not.
  76966. */
  76967. var ImageProcessingConfiguration = /** @class */ (function () {
  76968. function ImageProcessingConfiguration() {
  76969. /**
  76970. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76971. */
  76972. this.colorCurves = new BABYLON.ColorCurves();
  76973. this._colorCurvesEnabled = false;
  76974. this._colorGradingEnabled = false;
  76975. this._colorGradingWithGreenDepth = true;
  76976. this._colorGradingBGR = true;
  76977. this._exposure = 1.0;
  76978. this._toneMappingEnabled = false;
  76979. this._contrast = 1.0;
  76980. /**
  76981. * Vignette stretch size.
  76982. */
  76983. this.vignetteStretch = 0;
  76984. /**
  76985. * Vignette centre X Offset.
  76986. */
  76987. this.vignetteCentreX = 0;
  76988. /**
  76989. * Vignette centre Y Offset.
  76990. */
  76991. this.vignetteCentreY = 0;
  76992. /**
  76993. * Vignette weight or intensity of the vignette effect.
  76994. */
  76995. this.vignetteWeight = 1.5;
  76996. /**
  76997. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76998. * if vignetteEnabled is set to true.
  76999. */
  77000. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77001. /**
  77002. * Camera field of view used by the Vignette effect.
  77003. */
  77004. this.vignetteCameraFov = 0.5;
  77005. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77006. this._vignetteEnabled = false;
  77007. this._applyByPostProcess = false;
  77008. this._isEnabled = true;
  77009. /**
  77010. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77011. */
  77012. this.onUpdateParameters = new BABYLON.Observable();
  77013. }
  77014. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77015. /**
  77016. * Gets wether the color curves effect is enabled.
  77017. */
  77018. get: function () {
  77019. return this._colorCurvesEnabled;
  77020. },
  77021. /**
  77022. * Sets wether the color curves effect is enabled.
  77023. */
  77024. set: function (value) {
  77025. if (this._colorCurvesEnabled === value) {
  77026. return;
  77027. }
  77028. this._colorCurvesEnabled = value;
  77029. this._updateParameters();
  77030. },
  77031. enumerable: true,
  77032. configurable: true
  77033. });
  77034. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77035. /**
  77036. * Gets wether the color grading effect is enabled.
  77037. */
  77038. get: function () {
  77039. return this._colorGradingEnabled;
  77040. },
  77041. /**
  77042. * Sets wether the color grading effect is enabled.
  77043. */
  77044. set: function (value) {
  77045. if (this._colorGradingEnabled === value) {
  77046. return;
  77047. }
  77048. this._colorGradingEnabled = value;
  77049. this._updateParameters();
  77050. },
  77051. enumerable: true,
  77052. configurable: true
  77053. });
  77054. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77055. /**
  77056. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77057. */
  77058. get: function () {
  77059. return this._colorGradingWithGreenDepth;
  77060. },
  77061. /**
  77062. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77063. */
  77064. set: function (value) {
  77065. if (this._colorGradingWithGreenDepth === value) {
  77066. return;
  77067. }
  77068. this._colorGradingWithGreenDepth = value;
  77069. this._updateParameters();
  77070. },
  77071. enumerable: true,
  77072. configurable: true
  77073. });
  77074. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77075. /**
  77076. * Gets wether the color grading texture contains BGR values.
  77077. */
  77078. get: function () {
  77079. return this._colorGradingBGR;
  77080. },
  77081. /**
  77082. * Sets wether the color grading texture contains BGR values.
  77083. */
  77084. set: function (value) {
  77085. if (this._colorGradingBGR === value) {
  77086. return;
  77087. }
  77088. this._colorGradingBGR = value;
  77089. this._updateParameters();
  77090. },
  77091. enumerable: true,
  77092. configurable: true
  77093. });
  77094. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77095. /**
  77096. * Gets the Exposure used in the effect.
  77097. */
  77098. get: function () {
  77099. return this._exposure;
  77100. },
  77101. /**
  77102. * Sets the Exposure used in the effect.
  77103. */
  77104. set: function (value) {
  77105. if (this._exposure === value) {
  77106. return;
  77107. }
  77108. this._exposure = value;
  77109. this._updateParameters();
  77110. },
  77111. enumerable: true,
  77112. configurable: true
  77113. });
  77114. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77115. /**
  77116. * Gets wether the tone mapping effect is enabled.
  77117. */
  77118. get: function () {
  77119. return this._toneMappingEnabled;
  77120. },
  77121. /**
  77122. * Sets wether the tone mapping effect is enabled.
  77123. */
  77124. set: function (value) {
  77125. if (this._toneMappingEnabled === value) {
  77126. return;
  77127. }
  77128. this._toneMappingEnabled = value;
  77129. this._updateParameters();
  77130. },
  77131. enumerable: true,
  77132. configurable: true
  77133. });
  77134. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77135. /**
  77136. * Gets the contrast used in the effect.
  77137. */
  77138. get: function () {
  77139. return this._contrast;
  77140. },
  77141. /**
  77142. * Sets the contrast used in the effect.
  77143. */
  77144. set: function (value) {
  77145. if (this._contrast === value) {
  77146. return;
  77147. }
  77148. this._contrast = value;
  77149. this._updateParameters();
  77150. },
  77151. enumerable: true,
  77152. configurable: true
  77153. });
  77154. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77155. /**
  77156. * Gets the vignette blend mode allowing different kind of effect.
  77157. */
  77158. get: function () {
  77159. return this._vignetteBlendMode;
  77160. },
  77161. /**
  77162. * Sets the vignette blend mode allowing different kind of effect.
  77163. */
  77164. set: function (value) {
  77165. if (this._vignetteBlendMode === value) {
  77166. return;
  77167. }
  77168. this._vignetteBlendMode = value;
  77169. this._updateParameters();
  77170. },
  77171. enumerable: true,
  77172. configurable: true
  77173. });
  77174. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77175. /**
  77176. * Gets wether the vignette effect is enabled.
  77177. */
  77178. get: function () {
  77179. return this._vignetteEnabled;
  77180. },
  77181. /**
  77182. * Sets wether the vignette effect is enabled.
  77183. */
  77184. set: function (value) {
  77185. if (this._vignetteEnabled === value) {
  77186. return;
  77187. }
  77188. this._vignetteEnabled = value;
  77189. this._updateParameters();
  77190. },
  77191. enumerable: true,
  77192. configurable: true
  77193. });
  77194. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77195. /**
  77196. * Gets wether the image processing is applied through a post process or not.
  77197. */
  77198. get: function () {
  77199. return this._applyByPostProcess;
  77200. },
  77201. /**
  77202. * Sets wether the image processing is applied through a post process or not.
  77203. */
  77204. set: function (value) {
  77205. if (this._applyByPostProcess === value) {
  77206. return;
  77207. }
  77208. this._applyByPostProcess = value;
  77209. this._updateParameters();
  77210. },
  77211. enumerable: true,
  77212. configurable: true
  77213. });
  77214. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77215. /**
  77216. * Gets wether the image processing is enabled or not.
  77217. */
  77218. get: function () {
  77219. return this._isEnabled;
  77220. },
  77221. /**
  77222. * Sets wether the image processing is enabled or not.
  77223. */
  77224. set: function (value) {
  77225. if (this._isEnabled === value) {
  77226. return;
  77227. }
  77228. this._isEnabled = value;
  77229. this._updateParameters();
  77230. },
  77231. enumerable: true,
  77232. configurable: true
  77233. });
  77234. /**
  77235. * Method called each time the image processing information changes requires to recompile the effect.
  77236. */
  77237. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77238. this.onUpdateParameters.notifyObservers(this);
  77239. };
  77240. ImageProcessingConfiguration.prototype.getClassName = function () {
  77241. return "ImageProcessingConfiguration";
  77242. };
  77243. /**
  77244. * Prepare the list of uniforms associated with the Image Processing effects.
  77245. * @param uniformsList The list of uniforms used in the effect
  77246. * @param defines the list of defines currently in use
  77247. */
  77248. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77249. if (defines.EXPOSURE) {
  77250. uniforms.push("exposureLinear");
  77251. }
  77252. if (defines.CONTRAST) {
  77253. uniforms.push("contrast");
  77254. }
  77255. if (defines.COLORGRADING) {
  77256. uniforms.push("colorTransformSettings");
  77257. }
  77258. if (defines.VIGNETTE) {
  77259. uniforms.push("vInverseScreenSize");
  77260. uniforms.push("vignetteSettings1");
  77261. uniforms.push("vignetteSettings2");
  77262. }
  77263. if (defines.COLORCURVES) {
  77264. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77265. }
  77266. };
  77267. /**
  77268. * Prepare the list of samplers associated with the Image Processing effects.
  77269. * @param uniformsList The list of uniforms used in the effect
  77270. * @param defines the list of defines currently in use
  77271. */
  77272. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77273. if (defines.COLORGRADING) {
  77274. samplersList.push("txColorTransform");
  77275. }
  77276. };
  77277. /**
  77278. * Prepare the list of defines associated to the shader.
  77279. * @param defines the list of defines to complete
  77280. */
  77281. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77282. if (forPostProcess === void 0) { forPostProcess = false; }
  77283. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77284. defines.VIGNETTE = false;
  77285. defines.TONEMAPPING = false;
  77286. defines.CONTRAST = false;
  77287. defines.EXPOSURE = false;
  77288. defines.COLORCURVES = false;
  77289. defines.COLORGRADING = false;
  77290. defines.COLORGRADING3D = false;
  77291. defines.IMAGEPROCESSING = false;
  77292. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77293. return;
  77294. }
  77295. defines.VIGNETTE = this.vignetteEnabled;
  77296. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77297. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77298. defines.TONEMAPPING = this.toneMappingEnabled;
  77299. defines.CONTRAST = (this.contrast !== 1.0);
  77300. defines.EXPOSURE = (this.exposure !== 1.0);
  77301. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77302. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77303. if (defines.COLORGRADING) {
  77304. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77305. }
  77306. else {
  77307. defines.COLORGRADING3D = false;
  77308. }
  77309. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77310. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77311. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77312. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77313. };
  77314. /**
  77315. * Returns true if all the image processing information are ready.
  77316. */
  77317. ImageProcessingConfiguration.prototype.isReady = function () {
  77318. // Color Grading texure can not be none blocking.
  77319. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77320. };
  77321. /**
  77322. * Binds the image processing to the shader.
  77323. * @param effect The effect to bind to
  77324. */
  77325. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77326. if (aspectRatio === void 0) { aspectRatio = 1; }
  77327. // Color Curves
  77328. if (this._colorCurvesEnabled && this.colorCurves) {
  77329. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77330. }
  77331. // Vignette
  77332. if (this._vignetteEnabled) {
  77333. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77334. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77335. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77336. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77337. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77338. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77339. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77340. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77341. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77342. var vignettePower = -2.0 * this.vignetteWeight;
  77343. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77344. }
  77345. // Exposure
  77346. effect.setFloat("exposureLinear", this.exposure);
  77347. // Contrast
  77348. effect.setFloat("contrast", this.contrast);
  77349. // Color transform settings
  77350. if (this.colorGradingTexture) {
  77351. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77352. var textureSize = this.colorGradingTexture.getSize().height;
  77353. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77354. 0.5 / textureSize, // textureOffset
  77355. textureSize, // textureSize
  77356. this.colorGradingTexture.level // weight
  77357. );
  77358. }
  77359. };
  77360. /**
  77361. * Clones the current image processing instance.
  77362. * @return The cloned image processing
  77363. */
  77364. ImageProcessingConfiguration.prototype.clone = function () {
  77365. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77366. };
  77367. /**
  77368. * Serializes the current image processing instance to a json representation.
  77369. * @return a JSON representation
  77370. */
  77371. ImageProcessingConfiguration.prototype.serialize = function () {
  77372. return BABYLON.SerializationHelper.Serialize(this);
  77373. };
  77374. /**
  77375. * Parses the image processing from a json representation.
  77376. * @param source the JSON source to parse
  77377. * @return The parsed image processing
  77378. */
  77379. ImageProcessingConfiguration.Parse = function (source) {
  77380. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77381. };
  77382. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77383. /**
  77384. * Used to apply the vignette as a mix with the pixel color.
  77385. */
  77386. get: function () {
  77387. return this._VIGNETTEMODE_MULTIPLY;
  77388. },
  77389. enumerable: true,
  77390. configurable: true
  77391. });
  77392. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77393. /**
  77394. * Used to apply the vignette as a replacement of the pixel color.
  77395. */
  77396. get: function () {
  77397. return this._VIGNETTEMODE_OPAQUE;
  77398. },
  77399. enumerable: true,
  77400. configurable: true
  77401. });
  77402. // Static constants associated to the image processing.
  77403. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77404. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77405. __decorate([
  77406. BABYLON.serializeAsColorCurves()
  77407. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77408. __decorate([
  77409. BABYLON.serialize()
  77410. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77411. __decorate([
  77412. BABYLON.serializeAsTexture()
  77413. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77414. __decorate([
  77415. BABYLON.serialize()
  77416. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77417. __decorate([
  77418. BABYLON.serialize()
  77419. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77420. __decorate([
  77421. BABYLON.serialize()
  77422. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77423. __decorate([
  77424. BABYLON.serialize()
  77425. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77426. __decorate([
  77427. BABYLON.serialize()
  77428. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77429. __decorate([
  77430. BABYLON.serialize()
  77431. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77432. __decorate([
  77433. BABYLON.serialize()
  77434. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77435. __decorate([
  77436. BABYLON.serialize()
  77437. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77438. __decorate([
  77439. BABYLON.serialize()
  77440. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77441. __decorate([
  77442. BABYLON.serialize()
  77443. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77444. __decorate([
  77445. BABYLON.serializeAsColor4()
  77446. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77447. __decorate([
  77448. BABYLON.serialize()
  77449. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77450. __decorate([
  77451. BABYLON.serialize()
  77452. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77453. __decorate([
  77454. BABYLON.serialize()
  77455. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77456. __decorate([
  77457. BABYLON.serialize()
  77458. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77459. __decorate([
  77460. BABYLON.serialize()
  77461. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77462. return ImageProcessingConfiguration;
  77463. }());
  77464. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77465. })(BABYLON || (BABYLON = {}));
  77466. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77467. var BABYLON;
  77468. (function (BABYLON) {
  77469. /**
  77470. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77471. * It can help converting any input color in a desired output one. This can then be used to create effects
  77472. * from sepia, black and white to sixties or futuristic rendering...
  77473. *
  77474. * The only supported format is currently 3dl.
  77475. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77476. */
  77477. var ColorGradingTexture = /** @class */ (function (_super) {
  77478. __extends(ColorGradingTexture, _super);
  77479. /**
  77480. * Instantiates a ColorGradingTexture from the following parameters.
  77481. *
  77482. * @param url The location of the color gradind data (currently only supporting 3dl)
  77483. * @param scene The scene the texture will be used in
  77484. */
  77485. function ColorGradingTexture(url, scene) {
  77486. var _this = _super.call(this, scene) || this;
  77487. if (!url) {
  77488. return _this;
  77489. }
  77490. _this._engine = scene.getEngine();
  77491. _this._textureMatrix = BABYLON.Matrix.Identity();
  77492. _this.name = url;
  77493. _this.url = url;
  77494. _this.hasAlpha = false;
  77495. _this.isCube = false;
  77496. _this.is3D = _this._engine.webGLVersion > 1;
  77497. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77498. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77499. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77500. _this.anisotropicFilteringLevel = 1;
  77501. _this._texture = _this._getFromCache(url, true);
  77502. if (!_this._texture) {
  77503. if (!scene.useDelayedTextureLoading) {
  77504. _this.loadTexture();
  77505. }
  77506. else {
  77507. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77508. }
  77509. }
  77510. return _this;
  77511. }
  77512. /**
  77513. * Returns the texture matrix used in most of the material.
  77514. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77515. */
  77516. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77517. return this._textureMatrix;
  77518. };
  77519. /**
  77520. * Occurs when the file being loaded is a .3dl LUT file.
  77521. */
  77522. ColorGradingTexture.prototype.load3dlTexture = function () {
  77523. var engine = this._engine;
  77524. var texture;
  77525. if (engine.webGLVersion === 1) {
  77526. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77527. }
  77528. else {
  77529. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77530. }
  77531. this._texture = texture;
  77532. var callback = function (text) {
  77533. if (typeof text !== "string") {
  77534. return;
  77535. }
  77536. var data = null;
  77537. var tempData = null;
  77538. var line;
  77539. var lines = text.split('\n');
  77540. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77541. var maxColor = 0;
  77542. for (var i = 0; i < lines.length; i++) {
  77543. line = lines[i];
  77544. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77545. continue;
  77546. if (line.indexOf('#') === 0)
  77547. continue;
  77548. var words = line.split(" ");
  77549. if (size === 0) {
  77550. // Number of space + one
  77551. size = words.length;
  77552. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77553. tempData = new Float32Array(size * size * size * 4);
  77554. continue;
  77555. }
  77556. if (size != 0) {
  77557. var r = Math.max(parseInt(words[0]), 0);
  77558. var g = Math.max(parseInt(words[1]), 0);
  77559. var b = Math.max(parseInt(words[2]), 0);
  77560. maxColor = Math.max(r, maxColor);
  77561. maxColor = Math.max(g, maxColor);
  77562. maxColor = Math.max(b, maxColor);
  77563. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77564. if (tempData) {
  77565. tempData[pixelStorageIndex + 0] = r;
  77566. tempData[pixelStorageIndex + 1] = g;
  77567. tempData[pixelStorageIndex + 2] = b;
  77568. }
  77569. pixelIndexSlice++;
  77570. if (pixelIndexSlice % size == 0) {
  77571. pixelIndexH++;
  77572. pixelIndexSlice = 0;
  77573. if (pixelIndexH % size == 0) {
  77574. pixelIndexW++;
  77575. pixelIndexH = 0;
  77576. }
  77577. }
  77578. }
  77579. }
  77580. if (tempData && data) {
  77581. for (var i = 0; i < tempData.length; i++) {
  77582. if (i > 0 && (i + 1) % 4 === 0) {
  77583. data[i] = 255;
  77584. }
  77585. else {
  77586. var value = tempData[i];
  77587. data[i] = (value / maxColor * 255);
  77588. }
  77589. }
  77590. }
  77591. if (texture.is3D) {
  77592. texture.updateSize(size, size, size);
  77593. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77594. }
  77595. else {
  77596. texture.updateSize(size * size, size);
  77597. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77598. }
  77599. };
  77600. var scene = this.getScene();
  77601. if (scene) {
  77602. scene._loadFile(this.url, callback);
  77603. }
  77604. else {
  77605. this._engine._loadFile(this.url, callback);
  77606. }
  77607. return this._texture;
  77608. };
  77609. /**
  77610. * Starts the loading process of the texture.
  77611. */
  77612. ColorGradingTexture.prototype.loadTexture = function () {
  77613. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77614. this.load3dlTexture();
  77615. }
  77616. };
  77617. /**
  77618. * Clones the color gradind texture.
  77619. */
  77620. ColorGradingTexture.prototype.clone = function () {
  77621. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77622. // Base texture
  77623. newTexture.level = this.level;
  77624. return newTexture;
  77625. };
  77626. /**
  77627. * Called during delayed load for textures.
  77628. */
  77629. ColorGradingTexture.prototype.delayLoad = function () {
  77630. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77631. return;
  77632. }
  77633. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77634. this._texture = this._getFromCache(this.url, true);
  77635. if (!this._texture) {
  77636. this.loadTexture();
  77637. }
  77638. };
  77639. /**
  77640. * Parses a color grading texture serialized by Babylon.
  77641. * @param parsedTexture The texture information being parsedTexture
  77642. * @param scene The scene to load the texture in
  77643. * @param rootUrl The root url of the data assets to load
  77644. * @return A color gradind texture
  77645. */
  77646. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77647. var texture = null;
  77648. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77649. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77650. texture.name = parsedTexture.name;
  77651. texture.level = parsedTexture.level;
  77652. }
  77653. return texture;
  77654. };
  77655. /**
  77656. * Serializes the LUT texture to json format.
  77657. */
  77658. ColorGradingTexture.prototype.serialize = function () {
  77659. if (!this.name) {
  77660. return null;
  77661. }
  77662. var serializationObject = {};
  77663. serializationObject.name = this.name;
  77664. serializationObject.level = this.level;
  77665. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77666. return serializationObject;
  77667. };
  77668. /**
  77669. * Empty line regex stored for GC.
  77670. */
  77671. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77672. return ColorGradingTexture;
  77673. }(BABYLON.BaseTexture));
  77674. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77675. })(BABYLON || (BABYLON = {}));
  77676. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77677. var BABYLON;
  77678. (function (BABYLON) {
  77679. /**
  77680. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77681. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77682. * 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;
  77683. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77684. */
  77685. var ColorCurves = /** @class */ (function () {
  77686. function ColorCurves() {
  77687. this._dirty = true;
  77688. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77689. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77690. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77691. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77692. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77693. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77694. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77695. this._globalHue = 30;
  77696. this._globalDensity = 0;
  77697. this._globalSaturation = 0;
  77698. this._globalExposure = 0;
  77699. this._highlightsHue = 30;
  77700. this._highlightsDensity = 0;
  77701. this._highlightsSaturation = 0;
  77702. this._highlightsExposure = 0;
  77703. this._midtonesHue = 30;
  77704. this._midtonesDensity = 0;
  77705. this._midtonesSaturation = 0;
  77706. this._midtonesExposure = 0;
  77707. this._shadowsHue = 30;
  77708. this._shadowsDensity = 0;
  77709. this._shadowsSaturation = 0;
  77710. this._shadowsExposure = 0;
  77711. }
  77712. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77713. /**
  77714. * Gets the global Hue value.
  77715. * 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).
  77716. */
  77717. get: function () {
  77718. return this._globalHue;
  77719. },
  77720. /**
  77721. * Sets the global Hue value.
  77722. * 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).
  77723. */
  77724. set: function (value) {
  77725. this._globalHue = value;
  77726. this._dirty = true;
  77727. },
  77728. enumerable: true,
  77729. configurable: true
  77730. });
  77731. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77732. /**
  77733. * Gets the global Density value.
  77734. * 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.
  77735. * Values less than zero provide a filter of opposite hue.
  77736. */
  77737. get: function () {
  77738. return this._globalDensity;
  77739. },
  77740. /**
  77741. * Sets the global Density value.
  77742. * 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.
  77743. * Values less than zero provide a filter of opposite hue.
  77744. */
  77745. set: function (value) {
  77746. this._globalDensity = value;
  77747. this._dirty = true;
  77748. },
  77749. enumerable: true,
  77750. configurable: true
  77751. });
  77752. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77753. /**
  77754. * Gets the global Saturation value.
  77755. * 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.
  77756. */
  77757. get: function () {
  77758. return this._globalSaturation;
  77759. },
  77760. /**
  77761. * Sets the global Saturation value.
  77762. * 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.
  77763. */
  77764. set: function (value) {
  77765. this._globalSaturation = value;
  77766. this._dirty = true;
  77767. },
  77768. enumerable: true,
  77769. configurable: true
  77770. });
  77771. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77772. /**
  77773. * Gets the global Exposure value.
  77774. * 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.
  77775. */
  77776. get: function () {
  77777. return this._globalExposure;
  77778. },
  77779. /**
  77780. * Sets the global Exposure value.
  77781. * 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.
  77782. */
  77783. set: function (value) {
  77784. this._globalExposure = value;
  77785. this._dirty = true;
  77786. },
  77787. enumerable: true,
  77788. configurable: true
  77789. });
  77790. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77791. /**
  77792. * Gets the highlights Hue value.
  77793. * 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).
  77794. */
  77795. get: function () {
  77796. return this._highlightsHue;
  77797. },
  77798. /**
  77799. * Sets the highlights Hue value.
  77800. * 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).
  77801. */
  77802. set: function (value) {
  77803. this._highlightsHue = value;
  77804. this._dirty = true;
  77805. },
  77806. enumerable: true,
  77807. configurable: true
  77808. });
  77809. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77810. /**
  77811. * Gets the highlights Density value.
  77812. * 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.
  77813. * Values less than zero provide a filter of opposite hue.
  77814. */
  77815. get: function () {
  77816. return this._highlightsDensity;
  77817. },
  77818. /**
  77819. * Sets the highlights Density value.
  77820. * 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.
  77821. * Values less than zero provide a filter of opposite hue.
  77822. */
  77823. set: function (value) {
  77824. this._highlightsDensity = value;
  77825. this._dirty = true;
  77826. },
  77827. enumerable: true,
  77828. configurable: true
  77829. });
  77830. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77831. /**
  77832. * Gets the highlights Saturation value.
  77833. * 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.
  77834. */
  77835. get: function () {
  77836. return this._highlightsSaturation;
  77837. },
  77838. /**
  77839. * Sets the highlights Saturation value.
  77840. * 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.
  77841. */
  77842. set: function (value) {
  77843. this._highlightsSaturation = value;
  77844. this._dirty = true;
  77845. },
  77846. enumerable: true,
  77847. configurable: true
  77848. });
  77849. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77850. /**
  77851. * Gets the highlights Exposure value.
  77852. * 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.
  77853. */
  77854. get: function () {
  77855. return this._highlightsExposure;
  77856. },
  77857. /**
  77858. * Sets the highlights Exposure value.
  77859. * 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.
  77860. */
  77861. set: function (value) {
  77862. this._highlightsExposure = value;
  77863. this._dirty = true;
  77864. },
  77865. enumerable: true,
  77866. configurable: true
  77867. });
  77868. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  77869. /**
  77870. * Gets the midtones Hue value.
  77871. * 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).
  77872. */
  77873. get: function () {
  77874. return this._midtonesHue;
  77875. },
  77876. /**
  77877. * Sets the midtones Hue value.
  77878. * 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).
  77879. */
  77880. set: function (value) {
  77881. this._midtonesHue = value;
  77882. this._dirty = true;
  77883. },
  77884. enumerable: true,
  77885. configurable: true
  77886. });
  77887. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  77888. /**
  77889. * Gets the midtones Density value.
  77890. * 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.
  77891. * Values less than zero provide a filter of opposite hue.
  77892. */
  77893. get: function () {
  77894. return this._midtonesDensity;
  77895. },
  77896. /**
  77897. * Sets the midtones Density value.
  77898. * 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.
  77899. * Values less than zero provide a filter of opposite hue.
  77900. */
  77901. set: function (value) {
  77902. this._midtonesDensity = value;
  77903. this._dirty = true;
  77904. },
  77905. enumerable: true,
  77906. configurable: true
  77907. });
  77908. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  77909. /**
  77910. * Gets the midtones Saturation value.
  77911. * 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.
  77912. */
  77913. get: function () {
  77914. return this._midtonesSaturation;
  77915. },
  77916. /**
  77917. * Sets the midtones Saturation value.
  77918. * 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.
  77919. */
  77920. set: function (value) {
  77921. this._midtonesSaturation = value;
  77922. this._dirty = true;
  77923. },
  77924. enumerable: true,
  77925. configurable: true
  77926. });
  77927. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  77928. /**
  77929. * Gets the midtones Exposure value.
  77930. * 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.
  77931. */
  77932. get: function () {
  77933. return this._midtonesExposure;
  77934. },
  77935. /**
  77936. * Sets the midtones Exposure value.
  77937. * 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.
  77938. */
  77939. set: function (value) {
  77940. this._midtonesExposure = value;
  77941. this._dirty = true;
  77942. },
  77943. enumerable: true,
  77944. configurable: true
  77945. });
  77946. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77947. /**
  77948. * Gets the shadows Hue value.
  77949. * 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).
  77950. */
  77951. get: function () {
  77952. return this._shadowsHue;
  77953. },
  77954. /**
  77955. * Sets the shadows Hue value.
  77956. * 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).
  77957. */
  77958. set: function (value) {
  77959. this._shadowsHue = value;
  77960. this._dirty = true;
  77961. },
  77962. enumerable: true,
  77963. configurable: true
  77964. });
  77965. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77966. /**
  77967. * Gets the shadows Density value.
  77968. * 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.
  77969. * Values less than zero provide a filter of opposite hue.
  77970. */
  77971. get: function () {
  77972. return this._shadowsDensity;
  77973. },
  77974. /**
  77975. * Sets the shadows Density value.
  77976. * 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.
  77977. * Values less than zero provide a filter of opposite hue.
  77978. */
  77979. set: function (value) {
  77980. this._shadowsDensity = value;
  77981. this._dirty = true;
  77982. },
  77983. enumerable: true,
  77984. configurable: true
  77985. });
  77986. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77987. /**
  77988. * Gets the shadows Saturation value.
  77989. * 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.
  77990. */
  77991. get: function () {
  77992. return this._shadowsSaturation;
  77993. },
  77994. /**
  77995. * Sets the shadows Saturation value.
  77996. * 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.
  77997. */
  77998. set: function (value) {
  77999. this._shadowsSaturation = value;
  78000. this._dirty = true;
  78001. },
  78002. enumerable: true,
  78003. configurable: true
  78004. });
  78005. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78006. /**
  78007. * Gets the shadows Exposure value.
  78008. * 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.
  78009. */
  78010. get: function () {
  78011. return this._shadowsExposure;
  78012. },
  78013. /**
  78014. * Sets the shadows Exposure value.
  78015. * 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.
  78016. */
  78017. set: function (value) {
  78018. this._shadowsExposure = value;
  78019. this._dirty = true;
  78020. },
  78021. enumerable: true,
  78022. configurable: true
  78023. });
  78024. ColorCurves.prototype.getClassName = function () {
  78025. return "ColorCurves";
  78026. };
  78027. /**
  78028. * Binds the color curves to the shader.
  78029. * @param colorCurves The color curve to bind
  78030. * @param effect The effect to bind to
  78031. */
  78032. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78033. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78034. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78035. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78036. if (colorCurves._dirty) {
  78037. colorCurves._dirty = false;
  78038. // Fill in global info.
  78039. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78040. // Compute highlights info.
  78041. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78042. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78043. // Compute midtones info.
  78044. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78045. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78046. // Compute shadows info.
  78047. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78048. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78049. // Compute deltas (neutral is midtones).
  78050. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78051. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78052. }
  78053. if (effect) {
  78054. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78055. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78056. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78057. }
  78058. };
  78059. /**
  78060. * Prepare the list of uniforms associated with the ColorCurves effects.
  78061. * @param uniformsList The list of uniforms used in the effect
  78062. */
  78063. ColorCurves.PrepareUniforms = function (uniformsList) {
  78064. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78065. };
  78066. /**
  78067. * Returns color grading data based on a hue, density, saturation and exposure value.
  78068. * @param filterHue The hue of the color filter.
  78069. * @param filterDensity The density of the color filter.
  78070. * @param saturation The saturation.
  78071. * @param exposure The exposure.
  78072. * @param result The result data container.
  78073. */
  78074. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78075. if (hue == null) {
  78076. return;
  78077. }
  78078. hue = ColorCurves.clamp(hue, 0, 360);
  78079. density = ColorCurves.clamp(density, -100, 100);
  78080. saturation = ColorCurves.clamp(saturation, -100, 100);
  78081. exposure = ColorCurves.clamp(exposure, -100, 100);
  78082. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78083. // so that the maximum filter density is only 50% control. This provides fine control
  78084. // for small values and reasonable range.
  78085. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78086. density *= 0.5;
  78087. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78088. if (density < 0) {
  78089. density *= -1;
  78090. hue = (hue + 180) % 360;
  78091. }
  78092. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78093. result.scaleToRef(2, result);
  78094. result.a = 1 + 0.01 * saturation;
  78095. };
  78096. /**
  78097. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78098. * @param value The input slider value in range [-100,100].
  78099. * @returns Adjusted value.
  78100. */
  78101. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78102. value /= 100;
  78103. var x = Math.abs(value);
  78104. x = Math.pow(x, 2);
  78105. if (value < 0) {
  78106. x *= -1;
  78107. }
  78108. x *= 100;
  78109. return x;
  78110. };
  78111. /**
  78112. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78113. * @param hue The hue (H) input.
  78114. * @param saturation The saturation (S) input.
  78115. * @param brightness The brightness (B) input.
  78116. * @result An RGBA color represented as Vector4.
  78117. */
  78118. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78119. var h = ColorCurves.clamp(hue, 0, 360);
  78120. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78121. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78122. if (s === 0) {
  78123. result.r = v;
  78124. result.g = v;
  78125. result.b = v;
  78126. }
  78127. else {
  78128. // sector 0 to 5
  78129. h /= 60;
  78130. var i = Math.floor(h);
  78131. // fractional part of h
  78132. var f = h - i;
  78133. var p = v * (1 - s);
  78134. var q = v * (1 - s * f);
  78135. var t = v * (1 - s * (1 - f));
  78136. switch (i) {
  78137. case 0:
  78138. result.r = v;
  78139. result.g = t;
  78140. result.b = p;
  78141. break;
  78142. case 1:
  78143. result.r = q;
  78144. result.g = v;
  78145. result.b = p;
  78146. break;
  78147. case 2:
  78148. result.r = p;
  78149. result.g = v;
  78150. result.b = t;
  78151. break;
  78152. case 3:
  78153. result.r = p;
  78154. result.g = q;
  78155. result.b = v;
  78156. break;
  78157. case 4:
  78158. result.r = t;
  78159. result.g = p;
  78160. result.b = v;
  78161. break;
  78162. default: // case 5:
  78163. result.r = v;
  78164. result.g = p;
  78165. result.b = q;
  78166. break;
  78167. }
  78168. }
  78169. result.a = 1;
  78170. };
  78171. /**
  78172. * Returns a value clamped between min and max
  78173. * @param value The value to clamp
  78174. * @param min The minimum of value
  78175. * @param max The maximum of value
  78176. * @returns The clamped value.
  78177. */
  78178. ColorCurves.clamp = function (value, min, max) {
  78179. return Math.min(Math.max(value, min), max);
  78180. };
  78181. /**
  78182. * Clones the current color curve instance.
  78183. * @return The cloned curves
  78184. */
  78185. ColorCurves.prototype.clone = function () {
  78186. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78187. };
  78188. /**
  78189. * Serializes the current color curve instance to a json representation.
  78190. * @return a JSON representation
  78191. */
  78192. ColorCurves.prototype.serialize = function () {
  78193. return BABYLON.SerializationHelper.Serialize(this);
  78194. };
  78195. /**
  78196. * Parses the color curve from a json representation.
  78197. * @param source the JSON source to parse
  78198. * @return The parsed curves
  78199. */
  78200. ColorCurves.Parse = function (source) {
  78201. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78202. };
  78203. __decorate([
  78204. BABYLON.serialize()
  78205. ], ColorCurves.prototype, "_globalHue", void 0);
  78206. __decorate([
  78207. BABYLON.serialize()
  78208. ], ColorCurves.prototype, "_globalDensity", void 0);
  78209. __decorate([
  78210. BABYLON.serialize()
  78211. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78212. __decorate([
  78213. BABYLON.serialize()
  78214. ], ColorCurves.prototype, "_globalExposure", void 0);
  78215. __decorate([
  78216. BABYLON.serialize()
  78217. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78218. __decorate([
  78219. BABYLON.serialize()
  78220. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78221. __decorate([
  78222. BABYLON.serialize()
  78223. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78224. __decorate([
  78225. BABYLON.serialize()
  78226. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78227. __decorate([
  78228. BABYLON.serialize()
  78229. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78230. __decorate([
  78231. BABYLON.serialize()
  78232. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78233. __decorate([
  78234. BABYLON.serialize()
  78235. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78236. __decorate([
  78237. BABYLON.serialize()
  78238. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78239. return ColorCurves;
  78240. }());
  78241. BABYLON.ColorCurves = ColorCurves;
  78242. })(BABYLON || (BABYLON = {}));
  78243. //# sourceMappingURL=babylon.colorCurves.js.map
  78244. var BABYLON;
  78245. (function (BABYLON) {
  78246. var RefractionPostProcess = /** @class */ (function (_super) {
  78247. __extends(RefractionPostProcess, _super);
  78248. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78249. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78250. _this.color = color;
  78251. _this.depth = depth;
  78252. _this.colorLevel = colorLevel;
  78253. _this._ownRefractionTexture = true;
  78254. _this.onActivateObservable.add(function (cam) {
  78255. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78256. });
  78257. _this.onApplyObservable.add(function (effect) {
  78258. effect.setColor3("baseColor", _this.color);
  78259. effect.setFloat("depth", _this.depth);
  78260. effect.setFloat("colorLevel", _this.colorLevel);
  78261. effect.setTexture("refractionSampler", _this._refTexture);
  78262. });
  78263. return _this;
  78264. }
  78265. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78266. /**
  78267. * Gets or sets the refraction texture
  78268. * Please note that you are responsible for disposing the texture if you set it manually
  78269. */
  78270. get: function () {
  78271. return this._refTexture;
  78272. },
  78273. set: function (value) {
  78274. if (this._refTexture && this._ownRefractionTexture) {
  78275. this._refTexture.dispose();
  78276. }
  78277. this._refTexture = value;
  78278. this._ownRefractionTexture = false;
  78279. },
  78280. enumerable: true,
  78281. configurable: true
  78282. });
  78283. // Methods
  78284. RefractionPostProcess.prototype.dispose = function (camera) {
  78285. if (this._refTexture && this._ownRefractionTexture) {
  78286. this._refTexture.dispose();
  78287. this._refTexture = null;
  78288. }
  78289. _super.prototype.dispose.call(this, camera);
  78290. };
  78291. return RefractionPostProcess;
  78292. }(BABYLON.PostProcess));
  78293. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78294. })(BABYLON || (BABYLON = {}));
  78295. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78296. var BABYLON;
  78297. (function (BABYLON) {
  78298. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78299. __extends(BlackAndWhitePostProcess, _super);
  78300. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78301. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78302. _this.degree = 1;
  78303. _this.onApplyObservable.add(function (effect) {
  78304. effect.setFloat("degree", _this.degree);
  78305. });
  78306. return _this;
  78307. }
  78308. return BlackAndWhitePostProcess;
  78309. }(BABYLON.PostProcess));
  78310. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78311. })(BABYLON || (BABYLON = {}));
  78312. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78313. var BABYLON;
  78314. (function (BABYLON) {
  78315. /**
  78316. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78317. * input texture to perform effects such as edge detection or sharpening
  78318. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78319. */
  78320. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78321. __extends(ConvolutionPostProcess, _super);
  78322. /**
  78323. * Creates a new instance ConvolutionPostProcess
  78324. * @param name The name of the effect.
  78325. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78326. * @param options The required width/height ratio to downsize to before computing the render pass.
  78327. * @param camera The camera to apply the render pass to.
  78328. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78329. * @param engine The engine which the post process will be applied. (default: current engine)
  78330. * @param reusable If the post process can be reused on the same frame. (default: false)
  78331. * @param textureType Type of textures used when performing the post process. (default: 0)
  78332. */
  78333. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78334. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78335. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78336. _this.kernel = kernel;
  78337. _this.onApply = function (effect) {
  78338. effect.setFloat2("screenSize", _this.width, _this.height);
  78339. effect.setArray("kernel", _this.kernel);
  78340. };
  78341. return _this;
  78342. }
  78343. // Statics
  78344. /**
  78345. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78346. */
  78347. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78348. /**
  78349. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78350. */
  78351. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78352. /**
  78353. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78354. */
  78355. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78356. /**
  78357. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78358. */
  78359. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78360. /**
  78361. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78362. */
  78363. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78364. /**
  78365. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78366. */
  78367. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78368. return ConvolutionPostProcess;
  78369. }(BABYLON.PostProcess));
  78370. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78371. })(BABYLON || (BABYLON = {}));
  78372. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78373. var BABYLON;
  78374. (function (BABYLON) {
  78375. var FilterPostProcess = /** @class */ (function (_super) {
  78376. __extends(FilterPostProcess, _super);
  78377. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78378. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78379. _this.kernelMatrix = kernelMatrix;
  78380. _this.onApply = function (effect) {
  78381. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78382. };
  78383. return _this;
  78384. }
  78385. return FilterPostProcess;
  78386. }(BABYLON.PostProcess));
  78387. BABYLON.FilterPostProcess = FilterPostProcess;
  78388. })(BABYLON || (BABYLON = {}));
  78389. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78390. var BABYLON;
  78391. (function (BABYLON) {
  78392. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78393. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78394. __extends(VolumetricLightScatteringPostProcess, _super);
  78395. /**
  78396. * @constructor
  78397. * @param {string} name - The post-process name
  78398. * @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)
  78399. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78400. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78401. * @param {number} samples - The post-process quality, default 100
  78402. * @param {number} samplingMode - The post-process filtering mode
  78403. * @param {BABYLON.Engine} engine - The babylon engine
  78404. * @param {boolean} reusable - If the post-process is reusable
  78405. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78406. */
  78407. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78408. if (samples === void 0) { samples = 100; }
  78409. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78410. 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;
  78411. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78412. /**
  78413. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78414. */
  78415. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78416. /**
  78417. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78418. */
  78419. _this.useCustomMeshPosition = false;
  78420. /**
  78421. * If the post-process should inverse the light scattering direction
  78422. */
  78423. _this.invert = true;
  78424. /**
  78425. * Array containing the excluded meshes not rendered in the internal pass
  78426. */
  78427. _this.excludedMeshes = new Array();
  78428. /**
  78429. * Controls the overall intensity of the post-process
  78430. */
  78431. _this.exposure = 0.3;
  78432. /**
  78433. * Dissipates each sample's contribution in range [0, 1]
  78434. */
  78435. _this.decay = 0.96815;
  78436. /**
  78437. * Controls the overall intensity of each sample
  78438. */
  78439. _this.weight = 0.58767;
  78440. /**
  78441. * Controls the density of each sample
  78442. */
  78443. _this.density = 0.926;
  78444. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78445. engine = scene.getEngine();
  78446. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78447. // Configure mesh
  78448. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78449. // Configure
  78450. _this._createPass(scene, ratio.passRatio || ratio);
  78451. _this.onActivate = function (camera) {
  78452. if (!_this.isSupported) {
  78453. _this.dispose(camera);
  78454. }
  78455. _this.onActivate = null;
  78456. };
  78457. _this.onApplyObservable.add(function (effect) {
  78458. _this._updateMeshScreenCoordinates(scene);
  78459. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78460. effect.setFloat("exposure", _this.exposure);
  78461. effect.setFloat("decay", _this.decay);
  78462. effect.setFloat("weight", _this.weight);
  78463. effect.setFloat("density", _this.density);
  78464. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78465. });
  78466. return _this;
  78467. }
  78468. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78469. get: function () {
  78470. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78471. return false;
  78472. },
  78473. set: function (useDiffuseColor) {
  78474. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78475. },
  78476. enumerable: true,
  78477. configurable: true
  78478. });
  78479. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78480. return "VolumetricLightScatteringPostProcess";
  78481. };
  78482. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78483. var mesh = subMesh.getMesh();
  78484. // Render this.mesh as default
  78485. if (mesh === this.mesh && mesh.material) {
  78486. return mesh.material.isReady(mesh);
  78487. }
  78488. var defines = [];
  78489. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78490. var material = subMesh.getMaterial();
  78491. // Alpha test
  78492. if (material) {
  78493. if (material.needAlphaTesting()) {
  78494. defines.push("#define ALPHATEST");
  78495. }
  78496. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78497. attribs.push(BABYLON.VertexBuffer.UVKind);
  78498. defines.push("#define UV1");
  78499. }
  78500. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78501. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78502. defines.push("#define UV2");
  78503. }
  78504. }
  78505. // Bones
  78506. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78507. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78508. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78509. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78510. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78511. }
  78512. else {
  78513. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78514. }
  78515. // Instances
  78516. if (useInstances) {
  78517. defines.push("#define INSTANCES");
  78518. attribs.push("world0");
  78519. attribs.push("world1");
  78520. attribs.push("world2");
  78521. attribs.push("world3");
  78522. }
  78523. // Get correct effect
  78524. var join = defines.join("\n");
  78525. if (this._cachedDefines !== join) {
  78526. this._cachedDefines = join;
  78527. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78528. }
  78529. return this._volumetricLightScatteringPass.isReady();
  78530. };
  78531. /**
  78532. * Sets the new light position for light scattering effect
  78533. * @param {BABYLON.Vector3} The new custom light position
  78534. */
  78535. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78536. this.customMeshPosition = position;
  78537. };
  78538. /**
  78539. * Returns the light position for light scattering effect
  78540. * @return {BABYLON.Vector3} The custom light position
  78541. */
  78542. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78543. return this.customMeshPosition;
  78544. };
  78545. /**
  78546. * Disposes the internal assets and detaches the post-process from the camera
  78547. */
  78548. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78549. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78550. if (rttIndex !== -1) {
  78551. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78552. }
  78553. this._volumetricLightScatteringRTT.dispose();
  78554. _super.prototype.dispose.call(this, camera);
  78555. };
  78556. /**
  78557. * Returns the render target texture used by the post-process
  78558. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78559. */
  78560. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78561. return this._volumetricLightScatteringRTT;
  78562. };
  78563. // Private methods
  78564. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78565. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78566. return true;
  78567. }
  78568. return false;
  78569. };
  78570. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78571. var _this = this;
  78572. var engine = scene.getEngine();
  78573. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78574. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78575. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78576. this._volumetricLightScatteringRTT.renderList = null;
  78577. this._volumetricLightScatteringRTT.renderParticles = false;
  78578. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78579. var camera = this.getCamera();
  78580. if (camera) {
  78581. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78582. }
  78583. else {
  78584. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78585. }
  78586. // Custom render function for submeshes
  78587. var renderSubMesh = function (subMesh) {
  78588. var mesh = subMesh.getRenderingMesh();
  78589. if (_this._meshExcluded(mesh)) {
  78590. return;
  78591. }
  78592. var material = subMesh.getMaterial();
  78593. if (!material) {
  78594. return;
  78595. }
  78596. var scene = mesh.getScene();
  78597. var engine = scene.getEngine();
  78598. // Culling
  78599. engine.setState(material.backFaceCulling);
  78600. // Managing instances
  78601. var batch = mesh._getInstancesRenderList(subMesh._id);
  78602. if (batch.mustReturn) {
  78603. return;
  78604. }
  78605. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78606. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78607. var effect = _this._volumetricLightScatteringPass;
  78608. if (mesh === _this.mesh) {
  78609. if (subMesh.effect) {
  78610. effect = subMesh.effect;
  78611. }
  78612. else {
  78613. effect = material.getEffect();
  78614. }
  78615. }
  78616. engine.enableEffect(effect);
  78617. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78618. if (mesh === _this.mesh) {
  78619. material.bind(mesh.getWorldMatrix(), mesh);
  78620. }
  78621. else {
  78622. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78623. // Alpha test
  78624. if (material && material.needAlphaTesting()) {
  78625. var alphaTexture = material.getAlphaTestTexture();
  78626. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78627. if (alphaTexture) {
  78628. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78629. }
  78630. }
  78631. // Bones
  78632. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78633. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78634. }
  78635. }
  78636. // Draw
  78637. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78638. }
  78639. };
  78640. // Render target texture callbacks
  78641. var savedSceneClearColor;
  78642. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78643. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78644. savedSceneClearColor = scene.clearColor;
  78645. scene.clearColor = sceneClearColor;
  78646. });
  78647. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78648. scene.clearColor = savedSceneClearColor;
  78649. });
  78650. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78651. var engine = scene.getEngine();
  78652. var index;
  78653. if (depthOnlySubMeshes.length) {
  78654. engine.setColorWrite(false);
  78655. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78656. renderSubMesh(depthOnlySubMeshes.data[index]);
  78657. }
  78658. engine.setColorWrite(true);
  78659. }
  78660. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78661. renderSubMesh(opaqueSubMeshes.data[index]);
  78662. }
  78663. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78664. renderSubMesh(alphaTestSubMeshes.data[index]);
  78665. }
  78666. if (transparentSubMeshes.length) {
  78667. // Sort sub meshes
  78668. for (index = 0; index < transparentSubMeshes.length; index++) {
  78669. var submesh = transparentSubMeshes.data[index];
  78670. var boundingInfo = submesh.getBoundingInfo();
  78671. if (boundingInfo && scene.activeCamera) {
  78672. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78673. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78674. }
  78675. }
  78676. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78677. sortedArray.sort(function (a, b) {
  78678. // Alpha index first
  78679. if (a._alphaIndex > b._alphaIndex) {
  78680. return 1;
  78681. }
  78682. if (a._alphaIndex < b._alphaIndex) {
  78683. return -1;
  78684. }
  78685. // Then distance to camera
  78686. if (a._distanceToCamera < b._distanceToCamera) {
  78687. return 1;
  78688. }
  78689. if (a._distanceToCamera > b._distanceToCamera) {
  78690. return -1;
  78691. }
  78692. return 0;
  78693. });
  78694. // Render sub meshes
  78695. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78696. for (index = 0; index < sortedArray.length; index++) {
  78697. renderSubMesh(sortedArray[index]);
  78698. }
  78699. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78700. }
  78701. };
  78702. };
  78703. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78704. var transform = scene.getTransformMatrix();
  78705. var meshPosition;
  78706. if (this.useCustomMeshPosition) {
  78707. meshPosition = this.customMeshPosition;
  78708. }
  78709. else if (this.attachedNode) {
  78710. meshPosition = this.attachedNode.position;
  78711. }
  78712. else {
  78713. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78714. }
  78715. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78716. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78717. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78718. if (this.invert)
  78719. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78720. };
  78721. // Static methods
  78722. /**
  78723. * Creates a default mesh for the Volumeric Light Scattering post-process
  78724. * @param {string} The mesh name
  78725. * @param {BABYLON.Scene} The scene where to create the mesh
  78726. * @return {BABYLON.Mesh} the default mesh
  78727. */
  78728. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78729. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78730. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78731. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78732. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78733. mesh.material = material;
  78734. return mesh;
  78735. };
  78736. __decorate([
  78737. BABYLON.serializeAsVector3()
  78738. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78739. __decorate([
  78740. BABYLON.serialize()
  78741. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78742. __decorate([
  78743. BABYLON.serialize()
  78744. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78745. __decorate([
  78746. BABYLON.serializeAsMeshReference()
  78747. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78748. __decorate([
  78749. BABYLON.serialize()
  78750. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78751. __decorate([
  78752. BABYLON.serialize()
  78753. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78754. __decorate([
  78755. BABYLON.serialize()
  78756. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78757. __decorate([
  78758. BABYLON.serialize()
  78759. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78760. __decorate([
  78761. BABYLON.serialize()
  78762. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78763. return VolumetricLightScatteringPostProcess;
  78764. }(BABYLON.PostProcess));
  78765. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78766. })(BABYLON || (BABYLON = {}));
  78767. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78768. //
  78769. // This post-process allows the modification of rendered colors by using
  78770. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78771. //
  78772. // The object needs to be provided an url to a texture containing the color
  78773. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78774. // Use an image editing software to tweak the LUT to match your needs.
  78775. //
  78776. // For an example of a color LUT, see here:
  78777. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78778. // For explanations on color grading, see here:
  78779. // http://udn.epicgames.com/Three/ColorGrading.html
  78780. //
  78781. var BABYLON;
  78782. (function (BABYLON) {
  78783. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78784. __extends(ColorCorrectionPostProcess, _super);
  78785. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78786. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78787. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78788. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78789. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78790. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78791. _this.onApply = function (effect) {
  78792. effect.setTexture("colorTable", _this._colorTableTexture);
  78793. };
  78794. return _this;
  78795. }
  78796. return ColorCorrectionPostProcess;
  78797. }(BABYLON.PostProcess));
  78798. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78799. })(BABYLON || (BABYLON = {}));
  78800. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78801. var BABYLON;
  78802. (function (BABYLON) {
  78803. /** Defines operator used for tonemapping */
  78804. var TonemappingOperator;
  78805. (function (TonemappingOperator) {
  78806. /** Hable */
  78807. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78808. /** Reinhard */
  78809. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78810. /** HejiDawson */
  78811. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78812. /** Photographic */
  78813. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78814. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78815. ;
  78816. /**
  78817. * Defines a post process to apply tone mapping
  78818. */
  78819. var TonemapPostProcess = /** @class */ (function (_super) {
  78820. __extends(TonemapPostProcess, _super);
  78821. /**
  78822. * Creates a new TonemapPostProcess
  78823. * @param name defines the name of the postprocess
  78824. * @param _operator defines the operator to use
  78825. * @param exposureAdjustment defines the required exposure adjustement
  78826. * @param camera defines the camera to use (can be null)
  78827. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78828. * @param engine defines the hosting engine (can be ignore if camera is set)
  78829. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78830. */
  78831. function TonemapPostProcess(name, _operator,
  78832. /** Defines the required exposure adjustement */
  78833. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78834. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78835. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78836. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78837. _this._operator = _operator;
  78838. _this.exposureAdjustment = exposureAdjustment;
  78839. var defines = "#define ";
  78840. if (_this._operator === TonemappingOperator.Hable)
  78841. defines += "HABLE_TONEMAPPING";
  78842. else if (_this._operator === TonemappingOperator.Reinhard)
  78843. defines += "REINHARD_TONEMAPPING";
  78844. else if (_this._operator === TonemappingOperator.HejiDawson)
  78845. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78846. else if (_this._operator === TonemappingOperator.Photographic)
  78847. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78848. //sadly a second call to create the effect.
  78849. _this.updateEffect(defines);
  78850. _this.onApply = function (effect) {
  78851. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78852. };
  78853. return _this;
  78854. }
  78855. return TonemapPostProcess;
  78856. }(BABYLON.PostProcess));
  78857. BABYLON.TonemapPostProcess = TonemapPostProcess;
  78858. })(BABYLON || (BABYLON = {}));
  78859. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  78860. var BABYLON;
  78861. (function (BABYLON) {
  78862. var DisplayPassPostProcess = /** @class */ (function (_super) {
  78863. __extends(DisplayPassPostProcess, _super);
  78864. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  78865. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  78866. }
  78867. return DisplayPassPostProcess;
  78868. }(BABYLON.PostProcess));
  78869. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  78870. })(BABYLON || (BABYLON = {}));
  78871. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  78872. var BABYLON;
  78873. (function (BABYLON) {
  78874. var HighlightsPostProcess = /** @class */ (function (_super) {
  78875. __extends(HighlightsPostProcess, _super);
  78876. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78877. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78878. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78879. }
  78880. return HighlightsPostProcess;
  78881. }(BABYLON.PostProcess));
  78882. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  78883. })(BABYLON || (BABYLON = {}));
  78884. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  78885. var BABYLON;
  78886. (function (BABYLON) {
  78887. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  78888. __extends(ImageProcessingPostProcess, _super);
  78889. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  78890. if (camera === void 0) { camera = null; }
  78891. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78892. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  78893. _this._fromLinearSpace = true;
  78894. /**
  78895. * Defines cache preventing GC.
  78896. */
  78897. _this._defines = {
  78898. IMAGEPROCESSING: false,
  78899. VIGNETTE: false,
  78900. VIGNETTEBLENDMODEMULTIPLY: false,
  78901. VIGNETTEBLENDMODEOPAQUE: false,
  78902. TONEMAPPING: false,
  78903. CONTRAST: false,
  78904. COLORCURVES: false,
  78905. COLORGRADING: false,
  78906. COLORGRADING3D: false,
  78907. FROMLINEARSPACE: false,
  78908. SAMPLER3DGREENDEPTH: false,
  78909. SAMPLER3DBGRMAP: false,
  78910. IMAGEPROCESSINGPOSTPROCESS: false,
  78911. EXPOSURE: false,
  78912. };
  78913. // Setup the configuration as forced by the constructor. This would then not force the
  78914. // scene materials output in linear space and let untouched the default forward pass.
  78915. if (imageProcessingConfiguration) {
  78916. imageProcessingConfiguration.applyByPostProcess = true;
  78917. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  78918. // This will cause the shader to be compiled
  78919. _this.fromLinearSpace = false;
  78920. }
  78921. // Setup the default processing configuration to the scene.
  78922. else {
  78923. _this._attachImageProcessingConfiguration(null, true);
  78924. _this.imageProcessingConfiguration.applyByPostProcess = true;
  78925. }
  78926. _this.onApply = function (effect) {
  78927. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  78928. };
  78929. return _this;
  78930. }
  78931. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  78932. /**
  78933. * Gets the image processing configuration used either in this material.
  78934. */
  78935. get: function () {
  78936. return this._imageProcessingConfiguration;
  78937. },
  78938. /**
  78939. * Sets the Default image processing configuration used either in the this material.
  78940. *
  78941. * If sets to null, the scene one is in use.
  78942. */
  78943. set: function (value) {
  78944. this._attachImageProcessingConfiguration(value);
  78945. },
  78946. enumerable: true,
  78947. configurable: true
  78948. });
  78949. /**
  78950. * Attaches a new image processing configuration to the PBR Material.
  78951. * @param configuration
  78952. */
  78953. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78954. var _this = this;
  78955. if (doNotBuild === void 0) { doNotBuild = false; }
  78956. if (configuration === this._imageProcessingConfiguration) {
  78957. return;
  78958. }
  78959. // Detaches observer.
  78960. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78961. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78962. }
  78963. // Pick the scene configuration if needed.
  78964. if (!configuration) {
  78965. var scene = null;
  78966. var engine = this.getEngine();
  78967. var camera = this.getCamera();
  78968. if (camera) {
  78969. scene = camera.getScene();
  78970. }
  78971. else if (engine && engine.scenes) {
  78972. var scenes = engine.scenes;
  78973. scene = scenes[scenes.length - 1];
  78974. }
  78975. else {
  78976. scene = BABYLON.Engine.LastCreatedScene;
  78977. }
  78978. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78979. }
  78980. else {
  78981. this._imageProcessingConfiguration = configuration;
  78982. }
  78983. // Attaches observer.
  78984. if (this._imageProcessingConfiguration) {
  78985. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78986. _this._updateParameters();
  78987. });
  78988. }
  78989. // Ensure the effect will be rebuilt.
  78990. if (!doNotBuild) {
  78991. this._updateParameters();
  78992. }
  78993. };
  78994. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78995. /**
  78996. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78997. */
  78998. get: function () {
  78999. return this.imageProcessingConfiguration.colorCurves;
  79000. },
  79001. /**
  79002. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79003. */
  79004. set: function (value) {
  79005. this.imageProcessingConfiguration.colorCurves = value;
  79006. },
  79007. enumerable: true,
  79008. configurable: true
  79009. });
  79010. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79011. /**
  79012. * Gets wether the color curves effect is enabled.
  79013. */
  79014. get: function () {
  79015. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79016. },
  79017. /**
  79018. * Sets wether the color curves effect is enabled.
  79019. */
  79020. set: function (value) {
  79021. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79022. },
  79023. enumerable: true,
  79024. configurable: true
  79025. });
  79026. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79027. /**
  79028. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79029. */
  79030. get: function () {
  79031. return this.imageProcessingConfiguration.colorGradingTexture;
  79032. },
  79033. /**
  79034. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79035. */
  79036. set: function (value) {
  79037. this.imageProcessingConfiguration.colorGradingTexture = value;
  79038. },
  79039. enumerable: true,
  79040. configurable: true
  79041. });
  79042. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79043. /**
  79044. * Gets wether the color grading effect is enabled.
  79045. */
  79046. get: function () {
  79047. return this.imageProcessingConfiguration.colorGradingEnabled;
  79048. },
  79049. /**
  79050. * Gets wether the color grading effect is enabled.
  79051. */
  79052. set: function (value) {
  79053. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79054. },
  79055. enumerable: true,
  79056. configurable: true
  79057. });
  79058. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79059. /**
  79060. * Gets exposure used in the effect.
  79061. */
  79062. get: function () {
  79063. return this.imageProcessingConfiguration.exposure;
  79064. },
  79065. /**
  79066. * Sets exposure used in the effect.
  79067. */
  79068. set: function (value) {
  79069. this.imageProcessingConfiguration.exposure = value;
  79070. },
  79071. enumerable: true,
  79072. configurable: true
  79073. });
  79074. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79075. /**
  79076. * Gets wether tonemapping is enabled or not.
  79077. */
  79078. get: function () {
  79079. return this._imageProcessingConfiguration.toneMappingEnabled;
  79080. },
  79081. /**
  79082. * Sets wether tonemapping is enabled or not
  79083. */
  79084. set: function (value) {
  79085. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79086. },
  79087. enumerable: true,
  79088. configurable: true
  79089. });
  79090. ;
  79091. ;
  79092. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79093. /**
  79094. * Gets contrast used in the effect.
  79095. */
  79096. get: function () {
  79097. return this.imageProcessingConfiguration.contrast;
  79098. },
  79099. /**
  79100. * Sets contrast used in the effect.
  79101. */
  79102. set: function (value) {
  79103. this.imageProcessingConfiguration.contrast = value;
  79104. },
  79105. enumerable: true,
  79106. configurable: true
  79107. });
  79108. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79109. /**
  79110. * Gets Vignette stretch size.
  79111. */
  79112. get: function () {
  79113. return this.imageProcessingConfiguration.vignetteStretch;
  79114. },
  79115. /**
  79116. * Sets Vignette stretch size.
  79117. */
  79118. set: function (value) {
  79119. this.imageProcessingConfiguration.vignetteStretch = value;
  79120. },
  79121. enumerable: true,
  79122. configurable: true
  79123. });
  79124. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79125. /**
  79126. * Gets Vignette centre X Offset.
  79127. */
  79128. get: function () {
  79129. return this.imageProcessingConfiguration.vignetteCentreX;
  79130. },
  79131. /**
  79132. * Sets Vignette centre X Offset.
  79133. */
  79134. set: function (value) {
  79135. this.imageProcessingConfiguration.vignetteCentreX = value;
  79136. },
  79137. enumerable: true,
  79138. configurable: true
  79139. });
  79140. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79141. /**
  79142. * Gets Vignette centre Y Offset.
  79143. */
  79144. get: function () {
  79145. return this.imageProcessingConfiguration.vignetteCentreY;
  79146. },
  79147. /**
  79148. * Sets Vignette centre Y Offset.
  79149. */
  79150. set: function (value) {
  79151. this.imageProcessingConfiguration.vignetteCentreY = value;
  79152. },
  79153. enumerable: true,
  79154. configurable: true
  79155. });
  79156. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79157. /**
  79158. * Gets Vignette weight or intensity of the vignette effect.
  79159. */
  79160. get: function () {
  79161. return this.imageProcessingConfiguration.vignetteWeight;
  79162. },
  79163. /**
  79164. * Sets Vignette weight or intensity of the vignette effect.
  79165. */
  79166. set: function (value) {
  79167. this.imageProcessingConfiguration.vignetteWeight = value;
  79168. },
  79169. enumerable: true,
  79170. configurable: true
  79171. });
  79172. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79173. /**
  79174. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79175. * if vignetteEnabled is set to true.
  79176. */
  79177. get: function () {
  79178. return this.imageProcessingConfiguration.vignetteColor;
  79179. },
  79180. /**
  79181. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79182. * if vignetteEnabled is set to true.
  79183. */
  79184. set: function (value) {
  79185. this.imageProcessingConfiguration.vignetteColor = value;
  79186. },
  79187. enumerable: true,
  79188. configurable: true
  79189. });
  79190. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79191. /**
  79192. * Gets Camera field of view used by the Vignette effect.
  79193. */
  79194. get: function () {
  79195. return this.imageProcessingConfiguration.vignetteCameraFov;
  79196. },
  79197. /**
  79198. * Sets Camera field of view used by the Vignette effect.
  79199. */
  79200. set: function (value) {
  79201. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79202. },
  79203. enumerable: true,
  79204. configurable: true
  79205. });
  79206. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79207. /**
  79208. * Gets the vignette blend mode allowing different kind of effect.
  79209. */
  79210. get: function () {
  79211. return this.imageProcessingConfiguration.vignetteBlendMode;
  79212. },
  79213. /**
  79214. * Sets the vignette blend mode allowing different kind of effect.
  79215. */
  79216. set: function (value) {
  79217. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79218. },
  79219. enumerable: true,
  79220. configurable: true
  79221. });
  79222. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79223. /**
  79224. * Gets wether the vignette effect is enabled.
  79225. */
  79226. get: function () {
  79227. return this.imageProcessingConfiguration.vignetteEnabled;
  79228. },
  79229. /**
  79230. * Sets wether the vignette effect is enabled.
  79231. */
  79232. set: function (value) {
  79233. this.imageProcessingConfiguration.vignetteEnabled = value;
  79234. },
  79235. enumerable: true,
  79236. configurable: true
  79237. });
  79238. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79239. /**
  79240. * Gets wether the input of the processing is in Gamma or Linear Space.
  79241. */
  79242. get: function () {
  79243. return this._fromLinearSpace;
  79244. },
  79245. /**
  79246. * Sets wether the input of the processing is in Gamma or Linear Space.
  79247. */
  79248. set: function (value) {
  79249. if (this._fromLinearSpace === value) {
  79250. return;
  79251. }
  79252. this._fromLinearSpace = value;
  79253. this._updateParameters();
  79254. },
  79255. enumerable: true,
  79256. configurable: true
  79257. });
  79258. ImageProcessingPostProcess.prototype.getClassName = function () {
  79259. return "ImageProcessingPostProcess";
  79260. };
  79261. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79262. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79263. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79264. var defines = "";
  79265. for (var define in this._defines) {
  79266. if (this._defines[define]) {
  79267. defines += "#define " + define + ";\r\n";
  79268. }
  79269. }
  79270. var samplers = ["textureSampler"];
  79271. var uniforms = ["scale"];
  79272. if (BABYLON.ImageProcessingConfiguration) {
  79273. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79274. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79275. }
  79276. this.updateEffect(defines, uniforms, samplers);
  79277. };
  79278. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79279. _super.prototype.dispose.call(this, camera);
  79280. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79281. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79282. }
  79283. if (this._imageProcessingConfiguration) {
  79284. this.imageProcessingConfiguration.applyByPostProcess = false;
  79285. }
  79286. };
  79287. __decorate([
  79288. BABYLON.serialize()
  79289. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79290. return ImageProcessingPostProcess;
  79291. }(BABYLON.PostProcess));
  79292. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79293. })(BABYLON || (BABYLON = {}));
  79294. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79295. var BABYLON;
  79296. (function (BABYLON) {
  79297. /**
  79298. * Class used to store bone information
  79299. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79300. */
  79301. var Bone = /** @class */ (function (_super) {
  79302. __extends(Bone, _super);
  79303. /**
  79304. * Create a new bone
  79305. * @param name defines the bone name
  79306. * @param skeleton defines the parent skeleton
  79307. * @param parentBone defines the parent (can be null if the bone is the root)
  79308. * @param localMatrix defines the local matrix
  79309. * @param restPose defines the rest pose matrix
  79310. * @param baseMatrix defines the base matrix
  79311. * @param index defines index of the bone in the hiearchy
  79312. */
  79313. function Bone(
  79314. /**
  79315. * defines the bone name
  79316. */
  79317. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79318. if (parentBone === void 0) { parentBone = null; }
  79319. if (localMatrix === void 0) { localMatrix = null; }
  79320. if (restPose === void 0) { restPose = null; }
  79321. if (baseMatrix === void 0) { baseMatrix = null; }
  79322. if (index === void 0) { index = null; }
  79323. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79324. _this.name = name;
  79325. /**
  79326. * Gets the list of child bones
  79327. */
  79328. _this.children = new Array();
  79329. /** Gets the animations associated with this bone */
  79330. _this.animations = new Array();
  79331. /**
  79332. * @hidden Internal only
  79333. * Set this value to map this bone to a different index in the transform matrices
  79334. * Set this value to -1 to exclude the bone from the transform matrices
  79335. */
  79336. _this._index = null;
  79337. _this._absoluteTransform = new BABYLON.Matrix();
  79338. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79339. _this._scalingDeterminant = 1;
  79340. _this._worldTransform = new BABYLON.Matrix();
  79341. _this._needToDecompose = true;
  79342. _this._needToCompose = false;
  79343. _this._skeleton = skeleton;
  79344. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79345. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79346. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79347. _this._index = index;
  79348. skeleton.bones.push(_this);
  79349. _this.setParent(parentBone, false);
  79350. if (baseMatrix || localMatrix) {
  79351. _this._updateDifferenceMatrix();
  79352. }
  79353. return _this;
  79354. }
  79355. Object.defineProperty(Bone.prototype, "_matrix", {
  79356. /** @hidden */
  79357. get: function () {
  79358. this._compose();
  79359. return this._localMatrix;
  79360. },
  79361. /** @hidden */
  79362. set: function (value) {
  79363. this._localMatrix.copyFrom(value);
  79364. this._needToDecompose = true;
  79365. },
  79366. enumerable: true,
  79367. configurable: true
  79368. });
  79369. // Members
  79370. /**
  79371. * Gets the parent skeleton
  79372. * @returns a skeleton
  79373. */
  79374. Bone.prototype.getSkeleton = function () {
  79375. return this._skeleton;
  79376. };
  79377. /**
  79378. * Gets parent bone
  79379. * @returns a bone or null if the bone is the root of the bone hierarchy
  79380. */
  79381. Bone.prototype.getParent = function () {
  79382. return this._parent;
  79383. };
  79384. /**
  79385. * Sets the parent bone
  79386. * @param parent defines the parent (can be null if the bone is the root)
  79387. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79388. */
  79389. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79390. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79391. if (this._parent === parent) {
  79392. return;
  79393. }
  79394. if (this._parent) {
  79395. var index = this._parent.children.indexOf(this);
  79396. if (index !== -1) {
  79397. this._parent.children.splice(index, 1);
  79398. }
  79399. }
  79400. this._parent = parent;
  79401. if (this._parent) {
  79402. this._parent.children.push(this);
  79403. }
  79404. if (updateDifferenceMatrix) {
  79405. this._updateDifferenceMatrix();
  79406. }
  79407. this.markAsDirty();
  79408. };
  79409. /**
  79410. * Gets the local matrix
  79411. * @returns a matrix
  79412. */
  79413. Bone.prototype.getLocalMatrix = function () {
  79414. this._compose();
  79415. return this._localMatrix;
  79416. };
  79417. /**
  79418. * Gets the base matrix (initial matrix which remains unchanged)
  79419. * @returns a matrix
  79420. */
  79421. Bone.prototype.getBaseMatrix = function () {
  79422. return this._baseMatrix;
  79423. };
  79424. /**
  79425. * Gets the rest pose matrix
  79426. * @returns a matrix
  79427. */
  79428. Bone.prototype.getRestPose = function () {
  79429. return this._restPose;
  79430. };
  79431. /**
  79432. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79433. */
  79434. Bone.prototype.getWorldMatrix = function () {
  79435. return this._worldTransform;
  79436. };
  79437. /**
  79438. * Sets the local matrix to rest pose matrix
  79439. */
  79440. Bone.prototype.returnToRest = function () {
  79441. this.updateMatrix(this._restPose.clone());
  79442. };
  79443. /**
  79444. * Gets the inverse of the absolute transform matrix.
  79445. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79446. * @returns a matrix
  79447. */
  79448. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79449. return this._invertedAbsoluteTransform;
  79450. };
  79451. /**
  79452. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79453. * @returns a matrix
  79454. */
  79455. Bone.prototype.getAbsoluteTransform = function () {
  79456. return this._absoluteTransform;
  79457. };
  79458. Object.defineProperty(Bone.prototype, "position", {
  79459. // Properties (matches AbstractMesh properties)
  79460. /** Gets or sets current position (in local space) */
  79461. get: function () {
  79462. this._decompose();
  79463. return this._localPosition;
  79464. },
  79465. set: function (newPosition) {
  79466. this._decompose();
  79467. this._localPosition.copyFrom(newPosition);
  79468. this._markAsDirtyAndCompose();
  79469. },
  79470. enumerable: true,
  79471. configurable: true
  79472. });
  79473. Object.defineProperty(Bone.prototype, "rotation", {
  79474. /** Gets or sets current rotation (in local space) */
  79475. get: function () {
  79476. return this.getRotation();
  79477. },
  79478. set: function (newRotation) {
  79479. this.setRotation(newRotation);
  79480. },
  79481. enumerable: true,
  79482. configurable: true
  79483. });
  79484. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79485. /** Gets or sets current rotation quaternion (in local space) */
  79486. get: function () {
  79487. this._decompose();
  79488. return this._localRotation;
  79489. },
  79490. set: function (newRotation) {
  79491. this.setRotationQuaternion(newRotation);
  79492. },
  79493. enumerable: true,
  79494. configurable: true
  79495. });
  79496. Object.defineProperty(Bone.prototype, "scaling", {
  79497. /** Gets or sets current scaling (in local space) */
  79498. get: function () {
  79499. return this.getScale();
  79500. },
  79501. set: function (newScaling) {
  79502. this.setScale(newScaling);
  79503. },
  79504. enumerable: true,
  79505. configurable: true
  79506. });
  79507. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79508. /**
  79509. * Gets the animation properties override
  79510. */
  79511. get: function () {
  79512. return this._skeleton.animationPropertiesOverride;
  79513. },
  79514. enumerable: true,
  79515. configurable: true
  79516. });
  79517. // Methods
  79518. Bone.prototype._decompose = function () {
  79519. if (!this._needToDecompose) {
  79520. return;
  79521. }
  79522. this._needToDecompose = false;
  79523. if (!this._localScaling) {
  79524. this._localScaling = BABYLON.Vector3.Zero();
  79525. this._localRotation = BABYLON.Quaternion.Zero();
  79526. this._localPosition = BABYLON.Vector3.Zero();
  79527. }
  79528. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79529. };
  79530. Bone.prototype._compose = function () {
  79531. if (!this._needToCompose) {
  79532. return;
  79533. }
  79534. this._needToCompose = false;
  79535. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79536. };
  79537. /**
  79538. * Update the base and local matrices
  79539. * @param matrix defines the new base or local matrix
  79540. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79541. * @param updateLocalMatrix defines if the local matrix should be updated
  79542. */
  79543. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79544. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79545. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79546. this._baseMatrix.copyFrom(matrix);
  79547. if (updateDifferenceMatrix) {
  79548. this._updateDifferenceMatrix();
  79549. }
  79550. if (updateLocalMatrix) {
  79551. this._localMatrix.copyFrom(matrix);
  79552. this._markAsDirtyAndDecompose();
  79553. }
  79554. else {
  79555. this.markAsDirty();
  79556. }
  79557. };
  79558. /** @hidden */
  79559. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79560. if (updateChildren === void 0) { updateChildren = true; }
  79561. if (!rootMatrix) {
  79562. rootMatrix = this._baseMatrix;
  79563. }
  79564. if (this._parent) {
  79565. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79566. }
  79567. else {
  79568. this._absoluteTransform.copyFrom(rootMatrix);
  79569. }
  79570. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79571. if (updateChildren) {
  79572. for (var index = 0; index < this.children.length; index++) {
  79573. this.children[index]._updateDifferenceMatrix();
  79574. }
  79575. }
  79576. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79577. };
  79578. /**
  79579. * Flag the bone as dirty (Forcing it to update everything)
  79580. */
  79581. Bone.prototype.markAsDirty = function () {
  79582. this._currentRenderId++;
  79583. this._childRenderId++;
  79584. this._skeleton._markAsDirty();
  79585. };
  79586. Bone.prototype._markAsDirtyAndCompose = function () {
  79587. this.markAsDirty();
  79588. this._needToCompose = true;
  79589. };
  79590. Bone.prototype._markAsDirtyAndDecompose = function () {
  79591. this.markAsDirty();
  79592. this._needToDecompose = true;
  79593. };
  79594. /**
  79595. * Copy an animation range from another bone
  79596. * @param source defines the source bone
  79597. * @param rangeName defines the range name to copy
  79598. * @param frameOffset defines the frame offset
  79599. * @param rescaleAsRequired defines if rescaling must be applied if required
  79600. * @param skelDimensionsRatio defines the scaling ratio
  79601. * @returns true if operation was successful
  79602. */
  79603. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79604. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79605. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79606. // all animation may be coming from a library skeleton, so may need to create animation
  79607. if (this.animations.length === 0) {
  79608. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79609. this.animations[0].setKeys([]);
  79610. }
  79611. // get animation info / verify there is such a range from the source bone
  79612. var sourceRange = source.animations[0].getRange(rangeName);
  79613. if (!sourceRange) {
  79614. return false;
  79615. }
  79616. var from = sourceRange.from;
  79617. var to = sourceRange.to;
  79618. var sourceKeys = source.animations[0].getKeys();
  79619. // rescaling prep
  79620. var sourceBoneLength = source.length;
  79621. var sourceParent = source.getParent();
  79622. var parent = this.getParent();
  79623. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79624. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79625. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79626. var destKeys = this.animations[0].getKeys();
  79627. // loop vars declaration
  79628. var orig;
  79629. var origTranslation;
  79630. var mat;
  79631. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79632. orig = sourceKeys[key];
  79633. if (orig.frame >= from && orig.frame <= to) {
  79634. if (rescaleAsRequired) {
  79635. mat = orig.value.clone();
  79636. // scale based on parent ratio, when bone has parent
  79637. if (parentScalingReqd) {
  79638. origTranslation = mat.getTranslation();
  79639. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79640. // scale based on skeleton dimension ratio when root bone, and value is passed
  79641. }
  79642. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79643. origTranslation = mat.getTranslation();
  79644. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79645. // use original when root bone, and no data for skelDimensionsRatio
  79646. }
  79647. else {
  79648. mat = orig.value;
  79649. }
  79650. }
  79651. else {
  79652. mat = orig.value;
  79653. }
  79654. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79655. }
  79656. }
  79657. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79658. return true;
  79659. };
  79660. /**
  79661. * Translate the bone in local or world space
  79662. * @param vec The amount to translate the bone
  79663. * @param space The space that the translation is in
  79664. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79665. */
  79666. Bone.prototype.translate = function (vec, space, mesh) {
  79667. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79668. var lm = this.getLocalMatrix();
  79669. if (space == BABYLON.Space.LOCAL) {
  79670. lm.m[12] += vec.x;
  79671. lm.m[13] += vec.y;
  79672. lm.m[14] += vec.z;
  79673. }
  79674. else {
  79675. var wm = null;
  79676. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79677. if (mesh) {
  79678. wm = mesh.getWorldMatrix();
  79679. }
  79680. this._skeleton.computeAbsoluteTransforms();
  79681. var tmat = Bone._tmpMats[0];
  79682. var tvec = Bone._tmpVecs[0];
  79683. if (this._parent) {
  79684. if (mesh && wm) {
  79685. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79686. tmat.multiplyToRef(wm, tmat);
  79687. }
  79688. else {
  79689. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79690. }
  79691. }
  79692. tmat.m[12] = 0;
  79693. tmat.m[13] = 0;
  79694. tmat.m[14] = 0;
  79695. tmat.invert();
  79696. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79697. lm.m[12] += tvec.x;
  79698. lm.m[13] += tvec.y;
  79699. lm.m[14] += tvec.z;
  79700. }
  79701. this._markAsDirtyAndDecompose();
  79702. };
  79703. /**
  79704. * Set the postion of the bone in local or world space
  79705. * @param position The position to set the bone
  79706. * @param space The space that the position is in
  79707. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79708. */
  79709. Bone.prototype.setPosition = function (position, space, mesh) {
  79710. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79711. var lm = this.getLocalMatrix();
  79712. if (space == BABYLON.Space.LOCAL) {
  79713. lm.m[12] = position.x;
  79714. lm.m[13] = position.y;
  79715. lm.m[14] = position.z;
  79716. }
  79717. else {
  79718. var wm = null;
  79719. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79720. if (mesh) {
  79721. wm = mesh.getWorldMatrix();
  79722. }
  79723. this._skeleton.computeAbsoluteTransforms();
  79724. var tmat = Bone._tmpMats[0];
  79725. var vec = Bone._tmpVecs[0];
  79726. if (this._parent) {
  79727. if (mesh && wm) {
  79728. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79729. tmat.multiplyToRef(wm, tmat);
  79730. }
  79731. else {
  79732. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79733. }
  79734. }
  79735. tmat.invert();
  79736. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79737. lm.m[12] = vec.x;
  79738. lm.m[13] = vec.y;
  79739. lm.m[14] = vec.z;
  79740. }
  79741. this._markAsDirtyAndDecompose();
  79742. };
  79743. /**
  79744. * Set the absolute position of the bone (world space)
  79745. * @param position The position to set the bone
  79746. * @param mesh The mesh that this bone is attached to
  79747. */
  79748. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79749. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79750. };
  79751. /**
  79752. * Scale the bone on the x, y and z axes (in local space)
  79753. * @param x The amount to scale the bone on the x axis
  79754. * @param y The amount to scale the bone on the y axis
  79755. * @param z The amount to scale the bone on the z axis
  79756. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79757. */
  79758. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79759. if (scaleChildren === void 0) { scaleChildren = false; }
  79760. var locMat = this.getLocalMatrix();
  79761. // Apply new scaling on top of current local matrix
  79762. var scaleMat = Bone._tmpMats[0];
  79763. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79764. scaleMat.multiplyToRef(locMat, locMat);
  79765. // Invert scaling matrix and apply the inverse to all children
  79766. scaleMat.invert();
  79767. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79768. var child = _a[_i];
  79769. var cm = child.getLocalMatrix();
  79770. cm.multiplyToRef(scaleMat, cm);
  79771. cm.m[12] *= x;
  79772. cm.m[13] *= y;
  79773. cm.m[14] *= z;
  79774. child._markAsDirtyAndDecompose();
  79775. }
  79776. this._markAsDirtyAndDecompose();
  79777. if (scaleChildren) {
  79778. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79779. var child = _c[_b];
  79780. child.scale(x, y, z, scaleChildren);
  79781. }
  79782. }
  79783. };
  79784. /**
  79785. * Set the bone scaling in local space
  79786. * @param scale defines the scaling vector
  79787. */
  79788. Bone.prototype.setScale = function (scale) {
  79789. this._decompose();
  79790. this._localScaling.copyFrom(scale);
  79791. this._markAsDirtyAndCompose();
  79792. };
  79793. /**
  79794. * Gets the current scaling in local space
  79795. * @returns the current scaling vector
  79796. */
  79797. Bone.prototype.getScale = function () {
  79798. this._decompose();
  79799. return this._localScaling;
  79800. };
  79801. /**
  79802. * Gets the current scaling in local space and stores it in a target vector
  79803. * @param result defines the target vector
  79804. */
  79805. Bone.prototype.getScaleToRef = function (result) {
  79806. this._decompose();
  79807. result.copyFrom(this._localScaling);
  79808. };
  79809. /**
  79810. * Set the yaw, pitch, and roll of the bone in local or world space
  79811. * @param yaw The rotation of the bone on the y axis
  79812. * @param pitch The rotation of the bone on the x axis
  79813. * @param roll The rotation of the bone on the z axis
  79814. * @param space The space that the axes of rotation are in
  79815. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79816. */
  79817. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79818. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79819. if (space === BABYLON.Space.LOCAL) {
  79820. var quat = Bone._tmpQuat;
  79821. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79822. this.setRotationQuaternion(quat, space, mesh);
  79823. return;
  79824. }
  79825. var rotMatInv = Bone._tmpMats[0];
  79826. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79827. return;
  79828. }
  79829. var rotMat = Bone._tmpMats[1];
  79830. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79831. rotMatInv.multiplyToRef(rotMat, rotMat);
  79832. this._rotateWithMatrix(rotMat, space, mesh);
  79833. };
  79834. /**
  79835. * Add a rotation to the bone on an axis in local or world space
  79836. * @param axis The axis to rotate the bone on
  79837. * @param amount The amount to rotate the bone
  79838. * @param space The space that the axis is in
  79839. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79840. */
  79841. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79842. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79843. var rmat = Bone._tmpMats[0];
  79844. rmat.m[12] = 0;
  79845. rmat.m[13] = 0;
  79846. rmat.m[14] = 0;
  79847. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79848. this._rotateWithMatrix(rmat, space, mesh);
  79849. };
  79850. /**
  79851. * Set the rotation of the bone to a particular axis angle in local or world space
  79852. * @param axis The axis to rotate the bone on
  79853. * @param angle The angle that the bone should be rotated to
  79854. * @param space The space that the axis is in
  79855. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79856. */
  79857. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  79858. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79859. if (space === BABYLON.Space.LOCAL) {
  79860. var quat = Bone._tmpQuat;
  79861. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  79862. this.setRotationQuaternion(quat, space, mesh);
  79863. return;
  79864. }
  79865. var rotMatInv = Bone._tmpMats[0];
  79866. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79867. return;
  79868. }
  79869. var rotMat = Bone._tmpMats[1];
  79870. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  79871. rotMatInv.multiplyToRef(rotMat, rotMat);
  79872. this._rotateWithMatrix(rotMat, space, mesh);
  79873. };
  79874. /**
  79875. * Set the euler rotation of the bone in local of world space
  79876. * @param rotation The euler rotation that the bone should be set to
  79877. * @param space The space that the rotation is in
  79878. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79879. */
  79880. Bone.prototype.setRotation = function (rotation, space, mesh) {
  79881. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79882. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  79883. };
  79884. /**
  79885. * Set the quaternion rotation of the bone in local of world space
  79886. * @param quat The quaternion rotation that the bone should be set to
  79887. * @param space The space that the rotation is in
  79888. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79889. */
  79890. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  79891. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79892. if (space === BABYLON.Space.LOCAL) {
  79893. this._decompose();
  79894. this._localRotation.copyFrom(quat);
  79895. this._markAsDirtyAndCompose();
  79896. return;
  79897. }
  79898. var rotMatInv = Bone._tmpMats[0];
  79899. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79900. return;
  79901. }
  79902. var rotMat = Bone._tmpMats[1];
  79903. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  79904. rotMatInv.multiplyToRef(rotMat, rotMat);
  79905. this._rotateWithMatrix(rotMat, space, mesh);
  79906. };
  79907. /**
  79908. * Set the rotation matrix of the bone in local of world space
  79909. * @param rotMat The rotation matrix that the bone should be set to
  79910. * @param space The space that the rotation is in
  79911. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79912. */
  79913. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  79914. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79915. if (space === BABYLON.Space.LOCAL) {
  79916. var quat = Bone._tmpQuat;
  79917. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  79918. this.setRotationQuaternion(quat, space, mesh);
  79919. return;
  79920. }
  79921. var rotMatInv = Bone._tmpMats[0];
  79922. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79923. return;
  79924. }
  79925. var rotMat2 = Bone._tmpMats[1];
  79926. rotMat2.copyFrom(rotMat);
  79927. rotMatInv.multiplyToRef(rotMat, rotMat2);
  79928. this._rotateWithMatrix(rotMat2, space, mesh);
  79929. };
  79930. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  79931. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79932. var lmat = this.getLocalMatrix();
  79933. var lx = lmat.m[12];
  79934. var ly = lmat.m[13];
  79935. var lz = lmat.m[14];
  79936. var parent = this.getParent();
  79937. var parentScale = Bone._tmpMats[3];
  79938. var parentScaleInv = Bone._tmpMats[4];
  79939. if (parent && space == BABYLON.Space.WORLD) {
  79940. if (mesh) {
  79941. parentScale.copyFrom(mesh.getWorldMatrix());
  79942. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  79943. }
  79944. else {
  79945. parentScale.copyFrom(parent.getAbsoluteTransform());
  79946. }
  79947. parentScaleInv.copyFrom(parentScale);
  79948. parentScaleInv.invert();
  79949. lmat.multiplyToRef(parentScale, lmat);
  79950. lmat.multiplyToRef(rmat, lmat);
  79951. lmat.multiplyToRef(parentScaleInv, lmat);
  79952. }
  79953. else {
  79954. if (space == BABYLON.Space.WORLD && mesh) {
  79955. parentScale.copyFrom(mesh.getWorldMatrix());
  79956. parentScaleInv.copyFrom(parentScale);
  79957. parentScaleInv.invert();
  79958. lmat.multiplyToRef(parentScale, lmat);
  79959. lmat.multiplyToRef(rmat, lmat);
  79960. lmat.multiplyToRef(parentScaleInv, lmat);
  79961. }
  79962. else {
  79963. lmat.multiplyToRef(rmat, lmat);
  79964. }
  79965. }
  79966. lmat.m[12] = lx;
  79967. lmat.m[13] = ly;
  79968. lmat.m[14] = lz;
  79969. this.computeAbsoluteTransforms();
  79970. this._markAsDirtyAndDecompose();
  79971. };
  79972. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79973. var scaleMatrix = Bone._tmpMats[2];
  79974. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79975. if (mesh) {
  79976. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79977. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79978. }
  79979. rotMatInv.invert();
  79980. if (isNaN(rotMatInv.m[0])) {
  79981. // Matrix failed to invert.
  79982. // This can happen if scale is zero for example.
  79983. return false;
  79984. }
  79985. scaleMatrix.m[0] *= this._scalingDeterminant;
  79986. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79987. return true;
  79988. };
  79989. /**
  79990. * Get the position of the bone in local or world space
  79991. * @param space The space that the returned position is in
  79992. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79993. * @returns The position of the bone
  79994. */
  79995. Bone.prototype.getPosition = function (space, mesh) {
  79996. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79997. if (mesh === void 0) { mesh = null; }
  79998. var pos = BABYLON.Vector3.Zero();
  79999. this.getPositionToRef(space, mesh, pos);
  80000. return pos;
  80001. };
  80002. /**
  80003. * Copy the position of the bone to a vector3 in local or world space
  80004. * @param space The space that the returned position is in
  80005. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80006. * @param result The vector3 to copy the position to
  80007. */
  80008. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80009. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80010. if (space == BABYLON.Space.LOCAL) {
  80011. var lm = this.getLocalMatrix();
  80012. result.x = lm.m[12];
  80013. result.y = lm.m[13];
  80014. result.z = lm.m[14];
  80015. }
  80016. else {
  80017. var wm = null;
  80018. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80019. if (mesh) {
  80020. wm = mesh.getWorldMatrix();
  80021. }
  80022. this._skeleton.computeAbsoluteTransforms();
  80023. var tmat = Bone._tmpMats[0];
  80024. if (mesh && wm) {
  80025. tmat.copyFrom(this.getAbsoluteTransform());
  80026. tmat.multiplyToRef(wm, tmat);
  80027. }
  80028. else {
  80029. tmat = this.getAbsoluteTransform();
  80030. }
  80031. result.x = tmat.m[12];
  80032. result.y = tmat.m[13];
  80033. result.z = tmat.m[14];
  80034. }
  80035. };
  80036. /**
  80037. * Get the absolute position of the bone (world space)
  80038. * @param mesh The mesh that this bone is attached to
  80039. * @returns The absolute position of the bone
  80040. */
  80041. Bone.prototype.getAbsolutePosition = function (mesh) {
  80042. if (mesh === void 0) { mesh = null; }
  80043. var pos = BABYLON.Vector3.Zero();
  80044. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80045. return pos;
  80046. };
  80047. /**
  80048. * Copy the absolute position of the bone (world space) to the result param
  80049. * @param mesh The mesh that this bone is attached to
  80050. * @param result The vector3 to copy the absolute position to
  80051. */
  80052. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80053. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80054. };
  80055. /**
  80056. * Compute the absolute transforms of this bone and its children
  80057. */
  80058. Bone.prototype.computeAbsoluteTransforms = function () {
  80059. this._compose();
  80060. if (this._parent) {
  80061. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80062. }
  80063. else {
  80064. this._absoluteTransform.copyFrom(this._localMatrix);
  80065. var poseMatrix = this._skeleton.getPoseMatrix();
  80066. if (poseMatrix) {
  80067. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80068. }
  80069. }
  80070. var children = this.children;
  80071. var len = children.length;
  80072. for (var i = 0; i < len; i++) {
  80073. children[i].computeAbsoluteTransforms();
  80074. }
  80075. };
  80076. /**
  80077. * Get the world direction from an axis that is in the local space of the bone
  80078. * @param localAxis The local direction that is used to compute the world direction
  80079. * @param mesh The mesh that this bone is attached to
  80080. * @returns The world direction
  80081. */
  80082. Bone.prototype.getDirection = function (localAxis, mesh) {
  80083. if (mesh === void 0) { mesh = null; }
  80084. var result = BABYLON.Vector3.Zero();
  80085. this.getDirectionToRef(localAxis, mesh, result);
  80086. return result;
  80087. };
  80088. /**
  80089. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80090. * @param localAxis The local direction that is used to compute the world direction
  80091. * @param mesh The mesh that this bone is attached to
  80092. * @param result The vector3 that the world direction will be copied to
  80093. */
  80094. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80095. if (mesh === void 0) { mesh = null; }
  80096. var wm = null;
  80097. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80098. if (mesh) {
  80099. wm = mesh.getWorldMatrix();
  80100. }
  80101. this._skeleton.computeAbsoluteTransforms();
  80102. var mat = Bone._tmpMats[0];
  80103. mat.copyFrom(this.getAbsoluteTransform());
  80104. if (mesh && wm) {
  80105. mat.multiplyToRef(wm, mat);
  80106. }
  80107. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80108. result.normalize();
  80109. };
  80110. /**
  80111. * Get the euler rotation of the bone in local or world space
  80112. * @param space The space that the rotation should be in
  80113. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80114. * @returns The euler rotation
  80115. */
  80116. Bone.prototype.getRotation = function (space, mesh) {
  80117. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80118. if (mesh === void 0) { mesh = null; }
  80119. var result = BABYLON.Vector3.Zero();
  80120. this.getRotationToRef(space, mesh, result);
  80121. return result;
  80122. };
  80123. /**
  80124. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80125. * @param space The space that the rotation should be in
  80126. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80127. * @param result The vector3 that the rotation should be copied to
  80128. */
  80129. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80130. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80131. if (mesh === void 0) { mesh = null; }
  80132. var quat = Bone._tmpQuat;
  80133. this.getRotationQuaternionToRef(space, mesh, quat);
  80134. quat.toEulerAnglesToRef(result);
  80135. };
  80136. /**
  80137. * Get the quaternion rotation of the bone in either local or world space
  80138. * @param space The space that the rotation should be in
  80139. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80140. * @returns The quaternion rotation
  80141. */
  80142. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80143. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80144. if (mesh === void 0) { mesh = null; }
  80145. var result = BABYLON.Quaternion.Identity();
  80146. this.getRotationQuaternionToRef(space, mesh, result);
  80147. return result;
  80148. };
  80149. /**
  80150. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80151. * @param space The space that the rotation should be in
  80152. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80153. * @param result The quaternion that the rotation should be copied to
  80154. */
  80155. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80156. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80157. if (mesh === void 0) { mesh = null; }
  80158. if (space == BABYLON.Space.LOCAL) {
  80159. this._decompose();
  80160. result.copyFrom(this._localRotation);
  80161. }
  80162. else {
  80163. var mat = Bone._tmpMats[0];
  80164. var amat = this.getAbsoluteTransform();
  80165. if (mesh) {
  80166. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80167. }
  80168. else {
  80169. mat.copyFrom(amat);
  80170. }
  80171. mat.m[0] *= this._scalingDeterminant;
  80172. mat.m[1] *= this._scalingDeterminant;
  80173. mat.m[2] *= this._scalingDeterminant;
  80174. mat.decompose(undefined, result, undefined);
  80175. }
  80176. };
  80177. /**
  80178. * Get the rotation matrix of the bone in local or world space
  80179. * @param space The space that the rotation should be in
  80180. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80181. * @returns The rotation matrix
  80182. */
  80183. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80184. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80185. var result = BABYLON.Matrix.Identity();
  80186. this.getRotationMatrixToRef(space, mesh, result);
  80187. return result;
  80188. };
  80189. /**
  80190. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80191. * @param space The space that the rotation should be in
  80192. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80193. * @param result The quaternion that the rotation should be copied to
  80194. */
  80195. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80196. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80197. if (space == BABYLON.Space.LOCAL) {
  80198. this.getLocalMatrix().getRotationMatrixToRef(result);
  80199. }
  80200. else {
  80201. var mat = Bone._tmpMats[0];
  80202. var amat = this.getAbsoluteTransform();
  80203. if (mesh) {
  80204. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80205. }
  80206. else {
  80207. mat.copyFrom(amat);
  80208. }
  80209. mat.m[0] *= this._scalingDeterminant;
  80210. mat.m[1] *= this._scalingDeterminant;
  80211. mat.m[2] *= this._scalingDeterminant;
  80212. mat.getRotationMatrixToRef(result);
  80213. }
  80214. };
  80215. /**
  80216. * Get the world position of a point that is in the local space of the bone
  80217. * @param position The local position
  80218. * @param mesh The mesh that this bone is attached to
  80219. * @returns The world position
  80220. */
  80221. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80222. if (mesh === void 0) { mesh = null; }
  80223. var result = BABYLON.Vector3.Zero();
  80224. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80225. return result;
  80226. };
  80227. /**
  80228. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80229. * @param position The local position
  80230. * @param mesh The mesh that this bone is attached to
  80231. * @param result The vector3 that the world position should be copied to
  80232. */
  80233. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80234. if (mesh === void 0) { mesh = null; }
  80235. var wm = null;
  80236. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80237. if (mesh) {
  80238. wm = mesh.getWorldMatrix();
  80239. }
  80240. this._skeleton.computeAbsoluteTransforms();
  80241. var tmat = Bone._tmpMats[0];
  80242. if (mesh && wm) {
  80243. tmat.copyFrom(this.getAbsoluteTransform());
  80244. tmat.multiplyToRef(wm, tmat);
  80245. }
  80246. else {
  80247. tmat = this.getAbsoluteTransform();
  80248. }
  80249. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80250. };
  80251. /**
  80252. * Get the local position of a point that is in world space
  80253. * @param position The world position
  80254. * @param mesh The mesh that this bone is attached to
  80255. * @returns The local position
  80256. */
  80257. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80258. if (mesh === void 0) { mesh = null; }
  80259. var result = BABYLON.Vector3.Zero();
  80260. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80261. return result;
  80262. };
  80263. /**
  80264. * Get the local position of a point that is in world space and copy it to the result param
  80265. * @param position The world position
  80266. * @param mesh The mesh that this bone is attached to
  80267. * @param result The vector3 that the local position should be copied to
  80268. */
  80269. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80270. if (mesh === void 0) { mesh = null; }
  80271. var wm = null;
  80272. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80273. if (mesh) {
  80274. wm = mesh.getWorldMatrix();
  80275. }
  80276. this._skeleton.computeAbsoluteTransforms();
  80277. var tmat = Bone._tmpMats[0];
  80278. tmat.copyFrom(this.getAbsoluteTransform());
  80279. if (mesh && wm) {
  80280. tmat.multiplyToRef(wm, tmat);
  80281. }
  80282. tmat.invert();
  80283. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80284. };
  80285. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80286. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80287. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80288. return Bone;
  80289. }(BABYLON.Node));
  80290. BABYLON.Bone = Bone;
  80291. })(BABYLON || (BABYLON = {}));
  80292. //# sourceMappingURL=babylon.bone.js.map
  80293. var BABYLON;
  80294. (function (BABYLON) {
  80295. /**
  80296. * Class used to apply inverse kinematics to bones
  80297. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80298. */
  80299. var BoneIKController = /** @class */ (function () {
  80300. /**
  80301. * Creates a new BoneIKController
  80302. * @param mesh defines the mesh to control
  80303. * @param bone defines the bone to control
  80304. * @param options defines options to set up the controller
  80305. */
  80306. function BoneIKController(mesh, bone, options) {
  80307. /**
  80308. * Gets or sets the target position
  80309. */
  80310. this.targetPosition = BABYLON.Vector3.Zero();
  80311. /**
  80312. * Gets or sets the pole target position
  80313. */
  80314. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80315. /**
  80316. * Gets or sets the pole target local offset
  80317. */
  80318. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80319. /**
  80320. * Gets or sets the pole angle
  80321. */
  80322. this.poleAngle = 0;
  80323. /**
  80324. * 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)
  80325. */
  80326. this.slerpAmount = 1;
  80327. this._bone1Quat = BABYLON.Quaternion.Identity();
  80328. this._bone1Mat = BABYLON.Matrix.Identity();
  80329. this._bone2Ang = Math.PI;
  80330. this._maxAngle = Math.PI;
  80331. this._rightHandedSystem = false;
  80332. this._bendAxis = BABYLON.Vector3.Right();
  80333. this._slerping = false;
  80334. this._adjustRoll = 0;
  80335. this._bone2 = bone;
  80336. this._bone1 = bone.getParent();
  80337. if (!this._bone1) {
  80338. return;
  80339. }
  80340. this.mesh = mesh;
  80341. var bonePos = bone.getPosition();
  80342. if (bone.getAbsoluteTransform().determinant() > 0) {
  80343. this._rightHandedSystem = true;
  80344. this._bendAxis.x = 0;
  80345. this._bendAxis.y = 0;
  80346. this._bendAxis.z = -1;
  80347. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80348. this._adjustRoll = Math.PI * .5;
  80349. this._bendAxis.z = 1;
  80350. }
  80351. }
  80352. if (this._bone1.length) {
  80353. var boneScale1 = this._bone1.getScale();
  80354. var boneScale2 = this._bone2.getScale();
  80355. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80356. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80357. }
  80358. else if (this._bone1.children[0]) {
  80359. mesh.computeWorldMatrix(true);
  80360. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80361. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80362. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80363. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80364. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80365. }
  80366. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80367. this.maxAngle = Math.PI;
  80368. if (options) {
  80369. if (options.targetMesh) {
  80370. this.targetMesh = options.targetMesh;
  80371. this.targetMesh.computeWorldMatrix(true);
  80372. }
  80373. if (options.poleTargetMesh) {
  80374. this.poleTargetMesh = options.poleTargetMesh;
  80375. this.poleTargetMesh.computeWorldMatrix(true);
  80376. }
  80377. else if (options.poleTargetBone) {
  80378. this.poleTargetBone = options.poleTargetBone;
  80379. }
  80380. else if (this._bone1.getParent()) {
  80381. this.poleTargetBone = this._bone1.getParent();
  80382. }
  80383. if (options.poleTargetLocalOffset) {
  80384. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80385. }
  80386. if (options.poleAngle) {
  80387. this.poleAngle = options.poleAngle;
  80388. }
  80389. if (options.bendAxis) {
  80390. this._bendAxis.copyFrom(options.bendAxis);
  80391. }
  80392. if (options.maxAngle) {
  80393. this.maxAngle = options.maxAngle;
  80394. }
  80395. if (options.slerpAmount) {
  80396. this.slerpAmount = options.slerpAmount;
  80397. }
  80398. }
  80399. }
  80400. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80401. /**
  80402. * Gets or sets maximum allowed angle
  80403. */
  80404. get: function () {
  80405. return this._maxAngle;
  80406. },
  80407. set: function (value) {
  80408. this._setMaxAngle(value);
  80409. },
  80410. enumerable: true,
  80411. configurable: true
  80412. });
  80413. BoneIKController.prototype._setMaxAngle = function (ang) {
  80414. if (ang < 0) {
  80415. ang = 0;
  80416. }
  80417. if (ang > Math.PI || ang == undefined) {
  80418. ang = Math.PI;
  80419. }
  80420. this._maxAngle = ang;
  80421. var a = this._bone1Length;
  80422. var b = this._bone2Length;
  80423. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80424. };
  80425. /**
  80426. * Force the controller to update the bones
  80427. */
  80428. BoneIKController.prototype.update = function () {
  80429. var bone1 = this._bone1;
  80430. if (!bone1) {
  80431. return;
  80432. }
  80433. var target = this.targetPosition;
  80434. var poleTarget = this.poleTargetPosition;
  80435. var mat1 = BoneIKController._tmpMats[0];
  80436. var mat2 = BoneIKController._tmpMats[1];
  80437. if (this.targetMesh) {
  80438. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80439. }
  80440. if (this.poleTargetBone) {
  80441. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80442. }
  80443. else if (this.poleTargetMesh) {
  80444. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80445. }
  80446. var bonePos = BoneIKController._tmpVecs[0];
  80447. var zaxis = BoneIKController._tmpVecs[1];
  80448. var xaxis = BoneIKController._tmpVecs[2];
  80449. var yaxis = BoneIKController._tmpVecs[3];
  80450. var upAxis = BoneIKController._tmpVecs[4];
  80451. var _tmpQuat = BoneIKController._tmpQuat;
  80452. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80453. poleTarget.subtractToRef(bonePos, upAxis);
  80454. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80455. upAxis.y = 1;
  80456. }
  80457. else {
  80458. upAxis.normalize();
  80459. }
  80460. target.subtractToRef(bonePos, yaxis);
  80461. yaxis.normalize();
  80462. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80463. zaxis.normalize();
  80464. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80465. xaxis.normalize();
  80466. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80467. var a = this._bone1Length;
  80468. var b = this._bone2Length;
  80469. var c = BABYLON.Vector3.Distance(bonePos, target);
  80470. if (this._maxReach > 0) {
  80471. c = Math.min(this._maxReach, c);
  80472. }
  80473. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80474. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80475. if (acosa > 1) {
  80476. acosa = 1;
  80477. }
  80478. if (acosb > 1) {
  80479. acosb = 1;
  80480. }
  80481. if (acosa < -1) {
  80482. acosa = -1;
  80483. }
  80484. if (acosb < -1) {
  80485. acosb = -1;
  80486. }
  80487. var angA = Math.acos(acosa);
  80488. var angB = Math.acos(acosb);
  80489. var angC = -angA - angB;
  80490. if (this._rightHandedSystem) {
  80491. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80492. mat2.multiplyToRef(mat1, mat1);
  80493. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80494. mat2.multiplyToRef(mat1, mat1);
  80495. }
  80496. else {
  80497. var _tmpVec = BoneIKController._tmpVecs[5];
  80498. _tmpVec.copyFrom(this._bendAxis);
  80499. _tmpVec.x *= -1;
  80500. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80501. mat2.multiplyToRef(mat1, mat1);
  80502. }
  80503. if (this.poleAngle) {
  80504. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80505. mat1.multiplyToRef(mat2, mat1);
  80506. }
  80507. if (this._bone1) {
  80508. if (this.slerpAmount < 1) {
  80509. if (!this._slerping) {
  80510. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80511. }
  80512. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80513. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80514. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80515. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80516. this._slerping = true;
  80517. }
  80518. else {
  80519. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80520. this._bone1Mat.copyFrom(mat1);
  80521. this._slerping = false;
  80522. }
  80523. }
  80524. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80525. this._bone2Ang = angC;
  80526. };
  80527. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80528. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80529. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80530. return BoneIKController;
  80531. }());
  80532. BABYLON.BoneIKController = BoneIKController;
  80533. })(BABYLON || (BABYLON = {}));
  80534. //# sourceMappingURL=babylon.boneIKController.js.map
  80535. var BABYLON;
  80536. (function (BABYLON) {
  80537. /**
  80538. * Class used to make a bone look toward a point in space
  80539. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80540. */
  80541. var BoneLookController = /** @class */ (function () {
  80542. /**
  80543. * Create a BoneLookController
  80544. * @param mesh the mesh that the bone belongs to
  80545. * @param bone the bone that will be looking to the target
  80546. * @param target the target Vector3 to look at
  80547. * @param settings optional settings:
  80548. * * maxYaw: the maximum angle the bone will yaw to
  80549. * * minYaw: the minimum angle the bone will yaw to
  80550. * * maxPitch: the maximum angle the bone will pitch to
  80551. * * minPitch: the minimum angle the bone will yaw to
  80552. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80553. * * upAxis: the up axis of the coordinate system
  80554. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80555. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80556. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80557. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80558. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80559. * * adjustRoll: used to make an adjustment to the roll of the bone
  80560. **/
  80561. function BoneLookController(mesh, bone, target, options) {
  80562. /**
  80563. * The up axis of the coordinate system that is used when the bone is rotated
  80564. */
  80565. this.upAxis = BABYLON.Vector3.Up();
  80566. /**
  80567. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80568. */
  80569. this.upAxisSpace = BABYLON.Space.LOCAL;
  80570. /**
  80571. * Used to make an adjustment to the yaw of the bone
  80572. */
  80573. this.adjustYaw = 0;
  80574. /**
  80575. * Used to make an adjustment to the pitch of the bone
  80576. */
  80577. this.adjustPitch = 0;
  80578. /**
  80579. * Used to make an adjustment to the roll of the bone
  80580. */
  80581. this.adjustRoll = 0;
  80582. /**
  80583. * 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)
  80584. */
  80585. this.slerpAmount = 1;
  80586. this._boneQuat = BABYLON.Quaternion.Identity();
  80587. this._slerping = false;
  80588. this._firstFrameSkipped = false;
  80589. this._fowardAxis = BABYLON.Vector3.Forward();
  80590. this.mesh = mesh;
  80591. this.bone = bone;
  80592. this.target = target;
  80593. if (options) {
  80594. if (options.adjustYaw) {
  80595. this.adjustYaw = options.adjustYaw;
  80596. }
  80597. if (options.adjustPitch) {
  80598. this.adjustPitch = options.adjustPitch;
  80599. }
  80600. if (options.adjustRoll) {
  80601. this.adjustRoll = options.adjustRoll;
  80602. }
  80603. if (options.maxYaw != null) {
  80604. this.maxYaw = options.maxYaw;
  80605. }
  80606. else {
  80607. this.maxYaw = Math.PI;
  80608. }
  80609. if (options.minYaw != null) {
  80610. this.minYaw = options.minYaw;
  80611. }
  80612. else {
  80613. this.minYaw = -Math.PI;
  80614. }
  80615. if (options.maxPitch != null) {
  80616. this.maxPitch = options.maxPitch;
  80617. }
  80618. else {
  80619. this.maxPitch = Math.PI;
  80620. }
  80621. if (options.minPitch != null) {
  80622. this.minPitch = options.minPitch;
  80623. }
  80624. else {
  80625. this.minPitch = -Math.PI;
  80626. }
  80627. if (options.slerpAmount != null) {
  80628. this.slerpAmount = options.slerpAmount;
  80629. }
  80630. if (options.upAxis != null) {
  80631. this.upAxis = options.upAxis;
  80632. }
  80633. if (options.upAxisSpace != null) {
  80634. this.upAxisSpace = options.upAxisSpace;
  80635. }
  80636. if (options.yawAxis != null || options.pitchAxis != null) {
  80637. var newYawAxis = BABYLON.Axis.Y;
  80638. var newPitchAxis = BABYLON.Axis.X;
  80639. if (options.yawAxis != null) {
  80640. newYawAxis = options.yawAxis.clone();
  80641. newYawAxis.normalize();
  80642. }
  80643. if (options.pitchAxis != null) {
  80644. newPitchAxis = options.pitchAxis.clone();
  80645. newPitchAxis.normalize();
  80646. }
  80647. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80648. this._transformYawPitch = BABYLON.Matrix.Identity();
  80649. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80650. this._transformYawPitchInv = this._transformYawPitch.clone();
  80651. this._transformYawPitch.invert();
  80652. }
  80653. }
  80654. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80655. this.upAxisSpace = BABYLON.Space.LOCAL;
  80656. }
  80657. }
  80658. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80659. /**
  80660. * Gets or sets the minimum yaw angle that the bone can look to
  80661. */
  80662. get: function () {
  80663. return this._minYaw;
  80664. },
  80665. set: function (value) {
  80666. this._minYaw = value;
  80667. this._minYawSin = Math.sin(value);
  80668. this._minYawCos = Math.cos(value);
  80669. if (this._maxYaw != null) {
  80670. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80671. this._yawRange = this._maxYaw - this._minYaw;
  80672. }
  80673. },
  80674. enumerable: true,
  80675. configurable: true
  80676. });
  80677. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80678. /**
  80679. * Gets or sets the maximum yaw angle that the bone can look to
  80680. */
  80681. get: function () {
  80682. return this._maxYaw;
  80683. },
  80684. set: function (value) {
  80685. this._maxYaw = value;
  80686. this._maxYawSin = Math.sin(value);
  80687. this._maxYawCos = Math.cos(value);
  80688. if (this._minYaw != null) {
  80689. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80690. this._yawRange = this._maxYaw - this._minYaw;
  80691. }
  80692. },
  80693. enumerable: true,
  80694. configurable: true
  80695. });
  80696. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80697. /**
  80698. * Gets or sets the minimum pitch angle that the bone can look to
  80699. */
  80700. get: function () {
  80701. return this._minPitch;
  80702. },
  80703. set: function (value) {
  80704. this._minPitch = value;
  80705. this._minPitchTan = Math.tan(value);
  80706. },
  80707. enumerable: true,
  80708. configurable: true
  80709. });
  80710. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80711. /**
  80712. * Gets or sets the maximum pitch angle that the bone can look to
  80713. */
  80714. get: function () {
  80715. return this._maxPitch;
  80716. },
  80717. set: function (value) {
  80718. this._maxPitch = value;
  80719. this._maxPitchTan = Math.tan(value);
  80720. },
  80721. enumerable: true,
  80722. configurable: true
  80723. });
  80724. /**
  80725. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80726. */
  80727. BoneLookController.prototype.update = function () {
  80728. //skip the first frame when slerping so that the mesh rotation is correct
  80729. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80730. this._firstFrameSkipped = true;
  80731. return;
  80732. }
  80733. var bone = this.bone;
  80734. var bonePos = BoneLookController._tmpVecs[0];
  80735. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80736. var target = this.target;
  80737. var _tmpMat1 = BoneLookController._tmpMats[0];
  80738. var _tmpMat2 = BoneLookController._tmpMats[1];
  80739. var mesh = this.mesh;
  80740. var parentBone = bone.getParent();
  80741. var upAxis = BoneLookController._tmpVecs[1];
  80742. upAxis.copyFrom(this.upAxis);
  80743. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80744. if (this._transformYawPitch) {
  80745. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80746. }
  80747. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80748. }
  80749. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80750. mesh.getDirectionToRef(upAxis, upAxis);
  80751. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80752. upAxis.normalize();
  80753. }
  80754. }
  80755. var checkYaw = false;
  80756. var checkPitch = false;
  80757. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80758. checkYaw = true;
  80759. }
  80760. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80761. checkPitch = true;
  80762. }
  80763. if (checkYaw || checkPitch) {
  80764. var spaceMat = BoneLookController._tmpMats[2];
  80765. var spaceMatInv = BoneLookController._tmpMats[3];
  80766. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80767. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80768. }
  80769. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80770. spaceMat.copyFrom(mesh.getWorldMatrix());
  80771. }
  80772. else {
  80773. var forwardAxis = BoneLookController._tmpVecs[2];
  80774. forwardAxis.copyFrom(this._fowardAxis);
  80775. if (this._transformYawPitch) {
  80776. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80777. }
  80778. if (parentBone) {
  80779. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80780. }
  80781. else {
  80782. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80783. }
  80784. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80785. rightAxis.normalize();
  80786. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80787. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80788. }
  80789. spaceMat.invertToRef(spaceMatInv);
  80790. var xzlen = null;
  80791. if (checkPitch) {
  80792. var localTarget = BoneLookController._tmpVecs[3];
  80793. target.subtractToRef(bonePos, localTarget);
  80794. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80795. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80796. var pitch = Math.atan2(localTarget.y, xzlen);
  80797. var newPitch = pitch;
  80798. if (pitch > this._maxPitch) {
  80799. localTarget.y = this._maxPitchTan * xzlen;
  80800. newPitch = this._maxPitch;
  80801. }
  80802. else if (pitch < this._minPitch) {
  80803. localTarget.y = this._minPitchTan * xzlen;
  80804. newPitch = this._minPitch;
  80805. }
  80806. if (pitch != newPitch) {
  80807. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80808. localTarget.addInPlace(bonePos);
  80809. target = localTarget;
  80810. }
  80811. }
  80812. if (checkYaw) {
  80813. var localTarget = BoneLookController._tmpVecs[4];
  80814. target.subtractToRef(bonePos, localTarget);
  80815. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80816. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80817. var newYaw = yaw;
  80818. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80819. if (xzlen == null) {
  80820. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80821. }
  80822. if (this._yawRange > Math.PI) {
  80823. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80824. localTarget.z = this._maxYawCos * xzlen;
  80825. localTarget.x = this._maxYawSin * xzlen;
  80826. newYaw = this._maxYaw;
  80827. }
  80828. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80829. localTarget.z = this._minYawCos * xzlen;
  80830. localTarget.x = this._minYawSin * xzlen;
  80831. newYaw = this._minYaw;
  80832. }
  80833. }
  80834. else {
  80835. if (yaw > this._maxYaw) {
  80836. localTarget.z = this._maxYawCos * xzlen;
  80837. localTarget.x = this._maxYawSin * xzlen;
  80838. newYaw = this._maxYaw;
  80839. }
  80840. else if (yaw < this._minYaw) {
  80841. localTarget.z = this._minYawCos * xzlen;
  80842. localTarget.x = this._minYawSin * xzlen;
  80843. newYaw = this._minYaw;
  80844. }
  80845. }
  80846. }
  80847. if (this._slerping && this._yawRange > Math.PI) {
  80848. //are we going to be crossing into the min/max region?
  80849. var boneFwd = BoneLookController._tmpVecs[8];
  80850. boneFwd.copyFrom(BABYLON.Axis.Z);
  80851. if (this._transformYawPitch) {
  80852. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80853. }
  80854. var boneRotMat = BoneLookController._tmpMats[4];
  80855. this._boneQuat.toRotationMatrix(boneRotMat);
  80856. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80857. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  80858. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  80859. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  80860. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  80861. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  80862. if (angBtwTar > angBtwMidYaw) {
  80863. if (xzlen == null) {
  80864. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80865. }
  80866. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  80867. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  80868. if (angBtwMin < angBtwMax) {
  80869. newYaw = boneYaw + Math.PI * .75;
  80870. localTarget.z = Math.cos(newYaw) * xzlen;
  80871. localTarget.x = Math.sin(newYaw) * xzlen;
  80872. }
  80873. else {
  80874. newYaw = boneYaw - Math.PI * .75;
  80875. localTarget.z = Math.cos(newYaw) * xzlen;
  80876. localTarget.x = Math.sin(newYaw) * xzlen;
  80877. }
  80878. }
  80879. }
  80880. if (yaw != newYaw) {
  80881. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80882. localTarget.addInPlace(bonePos);
  80883. target = localTarget;
  80884. }
  80885. }
  80886. }
  80887. var zaxis = BoneLookController._tmpVecs[5];
  80888. var xaxis = BoneLookController._tmpVecs[6];
  80889. var yaxis = BoneLookController._tmpVecs[7];
  80890. var _tmpQuat = BoneLookController._tmpQuat;
  80891. target.subtractToRef(bonePos, zaxis);
  80892. zaxis.normalize();
  80893. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  80894. xaxis.normalize();
  80895. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  80896. yaxis.normalize();
  80897. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  80898. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  80899. return;
  80900. }
  80901. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  80902. return;
  80903. }
  80904. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  80905. return;
  80906. }
  80907. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  80908. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  80909. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  80910. }
  80911. if (this.slerpAmount < 1) {
  80912. if (!this._slerping) {
  80913. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  80914. }
  80915. if (this._transformYawPitch) {
  80916. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80917. }
  80918. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  80919. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  80920. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  80921. this._slerping = true;
  80922. }
  80923. else {
  80924. if (this._transformYawPitch) {
  80925. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80926. }
  80927. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  80928. this._slerping = false;
  80929. }
  80930. };
  80931. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  80932. var angDiff = ang2 - ang1;
  80933. angDiff %= Math.PI * 2;
  80934. if (angDiff > Math.PI) {
  80935. angDiff -= Math.PI * 2;
  80936. }
  80937. else if (angDiff < -Math.PI) {
  80938. angDiff += Math.PI * 2;
  80939. }
  80940. return angDiff;
  80941. };
  80942. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  80943. ang1 %= (2 * Math.PI);
  80944. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80945. ang2 %= (2 * Math.PI);
  80946. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80947. var ab = 0;
  80948. if (ang1 < ang2) {
  80949. ab = ang2 - ang1;
  80950. }
  80951. else {
  80952. ab = ang1 - ang2;
  80953. }
  80954. if (ab > Math.PI) {
  80955. ab = Math.PI * 2 - ab;
  80956. }
  80957. return ab;
  80958. };
  80959. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80960. ang %= (2 * Math.PI);
  80961. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80962. ang1 %= (2 * Math.PI);
  80963. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80964. ang2 %= (2 * Math.PI);
  80965. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80966. if (ang1 < ang2) {
  80967. if (ang > ang1 && ang < ang2) {
  80968. return true;
  80969. }
  80970. }
  80971. else {
  80972. if (ang > ang2 && ang < ang1) {
  80973. return true;
  80974. }
  80975. }
  80976. return false;
  80977. };
  80978. 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()];
  80979. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80980. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80981. return BoneLookController;
  80982. }());
  80983. BABYLON.BoneLookController = BoneLookController;
  80984. })(BABYLON || (BABYLON = {}));
  80985. //# sourceMappingURL=babylon.boneLookController.js.map
  80986. var BABYLON;
  80987. (function (BABYLON) {
  80988. /**
  80989. * Class used to handle skinning animations
  80990. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80991. */
  80992. var Skeleton = /** @class */ (function () {
  80993. /**
  80994. * Creates a new skeleton
  80995. * @param name defines the skeleton name
  80996. * @param id defines the skeleton Id
  80997. * @param scene defines the hosting scene
  80998. */
  80999. function Skeleton(
  81000. /** defines the skeleton name */
  81001. name,
  81002. /** defines the skeleton Id */
  81003. id, scene) {
  81004. this.name = name;
  81005. this.id = id;
  81006. /**
  81007. * Gets the list of child bones
  81008. */
  81009. this.bones = new Array();
  81010. /**
  81011. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81012. */
  81013. this.needInitialSkinMatrix = false;
  81014. this._isDirty = true;
  81015. this._meshesWithPoseMatrix = new Array();
  81016. this._identity = BABYLON.Matrix.Identity();
  81017. this._ranges = {};
  81018. this._lastAbsoluteTransformsUpdateId = -1;
  81019. /**
  81020. * Specifies if the skeleton should be serialized
  81021. */
  81022. this.doNotSerialize = false;
  81023. this._animationPropertiesOverride = null;
  81024. // Events
  81025. /**
  81026. * An observable triggered before computing the skeleton's matrices
  81027. */
  81028. this.onBeforeComputeObservable = new BABYLON.Observable();
  81029. this.bones = [];
  81030. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81031. scene.skeletons.push(this);
  81032. //make sure it will recalculate the matrix next time prepare is called.
  81033. this._isDirty = true;
  81034. }
  81035. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81036. /**
  81037. * Gets or sets the animation properties override
  81038. */
  81039. get: function () {
  81040. if (!this._animationPropertiesOverride) {
  81041. return this._scene.animationPropertiesOverride;
  81042. }
  81043. return this._animationPropertiesOverride;
  81044. },
  81045. set: function (value) {
  81046. this._animationPropertiesOverride = value;
  81047. },
  81048. enumerable: true,
  81049. configurable: true
  81050. });
  81051. // Members
  81052. /**
  81053. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81054. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81055. * @returns a Float32Array containing matrices data
  81056. */
  81057. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81058. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81059. return mesh._bonesTransformMatrices;
  81060. }
  81061. if (!this._transformMatrices) {
  81062. this.prepare();
  81063. }
  81064. return this._transformMatrices;
  81065. };
  81066. /**
  81067. * Gets the current hosting scene
  81068. * @returns a scene object
  81069. */
  81070. Skeleton.prototype.getScene = function () {
  81071. return this._scene;
  81072. };
  81073. // Methods
  81074. /**
  81075. * Gets a string representing the current skeleton data
  81076. * @param fullDetails defines a boolean indicating if we want a verbose version
  81077. * @returns a string representing the current skeleton data
  81078. */
  81079. Skeleton.prototype.toString = function (fullDetails) {
  81080. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81081. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81082. if (fullDetails) {
  81083. ret += ", Ranges: {";
  81084. var first = true;
  81085. for (var name_1 in this._ranges) {
  81086. if (first) {
  81087. ret += ", ";
  81088. first = false;
  81089. }
  81090. ret += name_1;
  81091. }
  81092. ret += "}";
  81093. }
  81094. return ret;
  81095. };
  81096. /**
  81097. * Get bone's index searching by name
  81098. * @param name defines bone's name to search for
  81099. * @return the indice of the bone. Returns -1 if not found
  81100. */
  81101. Skeleton.prototype.getBoneIndexByName = function (name) {
  81102. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81103. if (this.bones[boneIndex].name === name) {
  81104. return boneIndex;
  81105. }
  81106. }
  81107. return -1;
  81108. };
  81109. /**
  81110. * Creater a new animation range
  81111. * @param name defines the name of the range
  81112. * @param from defines the start key
  81113. * @param to defines the end key
  81114. */
  81115. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81116. // check name not already in use
  81117. if (!this._ranges[name]) {
  81118. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81119. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81120. if (this.bones[i].animations[0]) {
  81121. this.bones[i].animations[0].createRange(name, from, to);
  81122. }
  81123. }
  81124. }
  81125. };
  81126. /**
  81127. * Delete a specific animation range
  81128. * @param name defines the name of the range
  81129. * @param deleteFrames defines if frames must be removed as well
  81130. */
  81131. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81132. if (deleteFrames === void 0) { deleteFrames = true; }
  81133. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81134. if (this.bones[i].animations[0]) {
  81135. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81136. }
  81137. }
  81138. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81139. };
  81140. /**
  81141. * Gets a specific animation range
  81142. * @param name defines the name of the range to look for
  81143. * @returns the requested animation range or null if not found
  81144. */
  81145. Skeleton.prototype.getAnimationRange = function (name) {
  81146. return this._ranges[name];
  81147. };
  81148. /**
  81149. * Gets the list of all animation ranges defined on this skeleton
  81150. * @returns an array
  81151. */
  81152. Skeleton.prototype.getAnimationRanges = function () {
  81153. var animationRanges = [];
  81154. var name;
  81155. var i = 0;
  81156. for (name in this._ranges) {
  81157. animationRanges[i] = this._ranges[name];
  81158. i++;
  81159. }
  81160. return animationRanges;
  81161. };
  81162. /**
  81163. * Copy animation range from a source skeleton.
  81164. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81165. * @param source defines the source skeleton
  81166. * @param name defines the name of the range to copy
  81167. * @param rescaleAsRequired defines if rescaling must be applied if required
  81168. * @returns true if operation was successful
  81169. */
  81170. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81171. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81172. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81173. return false;
  81174. }
  81175. var ret = true;
  81176. var frameOffset = this._getHighestAnimationFrame() + 1;
  81177. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81178. var boneDict = {};
  81179. var sourceBones = source.bones;
  81180. var nBones;
  81181. var i;
  81182. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81183. boneDict[sourceBones[i].name] = sourceBones[i];
  81184. }
  81185. if (this.bones.length !== sourceBones.length) {
  81186. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81187. ret = false;
  81188. }
  81189. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81190. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81191. var boneName = this.bones[i].name;
  81192. var sourceBone = boneDict[boneName];
  81193. if (sourceBone) {
  81194. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81195. }
  81196. else {
  81197. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81198. ret = false;
  81199. }
  81200. }
  81201. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81202. var range = source.getAnimationRange(name);
  81203. if (range) {
  81204. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81205. }
  81206. return ret;
  81207. };
  81208. /**
  81209. * Forces the skeleton to go to rest pose
  81210. */
  81211. Skeleton.prototype.returnToRest = function () {
  81212. for (var index = 0; index < this.bones.length; index++) {
  81213. this.bones[index].returnToRest();
  81214. }
  81215. };
  81216. Skeleton.prototype._getHighestAnimationFrame = function () {
  81217. var ret = 0;
  81218. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81219. if (this.bones[i].animations[0]) {
  81220. var highest = this.bones[i].animations[0].getHighestFrame();
  81221. if (ret < highest) {
  81222. ret = highest;
  81223. }
  81224. }
  81225. }
  81226. return ret;
  81227. };
  81228. /**
  81229. * Begin a specific animation range
  81230. * @param name defines the name of the range to start
  81231. * @param loop defines if looping must be turned on (false by default)
  81232. * @param speedRatio defines the speed ratio to apply (1 by default)
  81233. * @param onAnimationEnd defines a callback which will be called when animation will end
  81234. * @returns a new animatable
  81235. */
  81236. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81237. var range = this.getAnimationRange(name);
  81238. if (!range) {
  81239. return null;
  81240. }
  81241. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81242. };
  81243. /** @hidden */
  81244. Skeleton.prototype._markAsDirty = function () {
  81245. this._isDirty = true;
  81246. };
  81247. /** @hidden */
  81248. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81249. this._meshesWithPoseMatrix.push(mesh);
  81250. };
  81251. /** @hidden */
  81252. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81253. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81254. if (index > -1) {
  81255. this._meshesWithPoseMatrix.splice(index, 1);
  81256. }
  81257. };
  81258. /** @hidden */
  81259. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81260. this.onBeforeComputeObservable.notifyObservers(this);
  81261. for (var index = 0; index < this.bones.length; index++) {
  81262. var bone = this.bones[index];
  81263. var parentBone = bone.getParent();
  81264. if (parentBone) {
  81265. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81266. }
  81267. else {
  81268. if (initialSkinMatrix) {
  81269. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81270. }
  81271. else {
  81272. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81273. }
  81274. }
  81275. if (bone._index !== -1) {
  81276. var mappedIndex = bone._index === null ? index : bone._index;
  81277. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81278. }
  81279. }
  81280. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81281. };
  81282. /**
  81283. * Build all resources required to render a skeleton
  81284. */
  81285. Skeleton.prototype.prepare = function () {
  81286. if (!this._isDirty) {
  81287. return;
  81288. }
  81289. if (this.needInitialSkinMatrix) {
  81290. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81291. var mesh = this._meshesWithPoseMatrix[index];
  81292. var poseMatrix = mesh.getPoseMatrix();
  81293. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81294. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81295. }
  81296. if (this._synchronizedWithMesh !== mesh) {
  81297. this._synchronizedWithMesh = mesh;
  81298. // Prepare bones
  81299. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81300. var bone = this.bones[boneIndex];
  81301. if (!bone.getParent()) {
  81302. var matrix = bone.getBaseMatrix();
  81303. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81304. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81305. }
  81306. }
  81307. }
  81308. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81309. }
  81310. }
  81311. else {
  81312. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81313. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81314. }
  81315. this._computeTransformMatrices(this._transformMatrices, null);
  81316. }
  81317. this._isDirty = false;
  81318. this._scene._activeBones.addCount(this.bones.length, false);
  81319. };
  81320. /**
  81321. * Gets the list of animatables currently running for this skeleton
  81322. * @returns an array of animatables
  81323. */
  81324. Skeleton.prototype.getAnimatables = function () {
  81325. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81326. this._animatables = [];
  81327. for (var index = 0; index < this.bones.length; index++) {
  81328. this._animatables.push(this.bones[index]);
  81329. }
  81330. }
  81331. return this._animatables;
  81332. };
  81333. /**
  81334. * Clone the current skeleton
  81335. * @param name defines the name of the new skeleton
  81336. * @param id defines the id of the enw skeleton
  81337. * @returns the new skeleton
  81338. */
  81339. Skeleton.prototype.clone = function (name, id) {
  81340. var result = new Skeleton(name, id || name, this._scene);
  81341. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81342. for (var index = 0; index < this.bones.length; index++) {
  81343. var source = this.bones[index];
  81344. var parentBone = null;
  81345. var parent_1 = source.getParent();
  81346. if (parent_1) {
  81347. var parentIndex = this.bones.indexOf(parent_1);
  81348. parentBone = result.bones[parentIndex];
  81349. }
  81350. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81351. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81352. }
  81353. if (this._ranges) {
  81354. result._ranges = {};
  81355. for (var rangeName in this._ranges) {
  81356. var range = this._ranges[rangeName];
  81357. if (range) {
  81358. result._ranges[rangeName] = range.clone();
  81359. }
  81360. }
  81361. }
  81362. this._isDirty = true;
  81363. return result;
  81364. };
  81365. /**
  81366. * Enable animation blending for this skeleton
  81367. * @param blendingSpeed defines the blending speed to apply
  81368. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81369. */
  81370. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81371. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81372. this.bones.forEach(function (bone) {
  81373. bone.animations.forEach(function (animation) {
  81374. animation.enableBlending = true;
  81375. animation.blendingSpeed = blendingSpeed;
  81376. });
  81377. });
  81378. };
  81379. /**
  81380. * Releases all resources associated with the current skeleton
  81381. */
  81382. Skeleton.prototype.dispose = function () {
  81383. this._meshesWithPoseMatrix = [];
  81384. // Animations
  81385. this.getScene().stopAnimation(this);
  81386. // Remove from scene
  81387. this.getScene().removeSkeleton(this);
  81388. };
  81389. /**
  81390. * Serialize the skeleton in a JSON object
  81391. * @returns a JSON object
  81392. */
  81393. Skeleton.prototype.serialize = function () {
  81394. var serializationObject = {};
  81395. serializationObject.name = this.name;
  81396. serializationObject.id = this.id;
  81397. if (this.dimensionsAtRest) {
  81398. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81399. }
  81400. serializationObject.bones = [];
  81401. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81402. for (var index = 0; index < this.bones.length; index++) {
  81403. var bone = this.bones[index];
  81404. var parent_2 = bone.getParent();
  81405. var serializedBone = {
  81406. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81407. name: bone.name,
  81408. matrix: bone.getBaseMatrix().toArray(),
  81409. rest: bone.getRestPose().toArray()
  81410. };
  81411. serializationObject.bones.push(serializedBone);
  81412. if (bone.length) {
  81413. serializedBone.length = bone.length;
  81414. }
  81415. if (bone.metadata) {
  81416. serializedBone.metadata = bone.metadata;
  81417. }
  81418. if (bone.animations && bone.animations.length > 0) {
  81419. serializedBone.animation = bone.animations[0].serialize();
  81420. }
  81421. serializationObject.ranges = [];
  81422. for (var name in this._ranges) {
  81423. var source = this._ranges[name];
  81424. if (!source) {
  81425. continue;
  81426. }
  81427. var range = {};
  81428. range.name = name;
  81429. range.from = source.from;
  81430. range.to = source.to;
  81431. serializationObject.ranges.push(range);
  81432. }
  81433. }
  81434. return serializationObject;
  81435. };
  81436. /**
  81437. * Creates a new skeleton from serialized data
  81438. * @param parsedSkeleton defines the serialized data
  81439. * @param scene defines the hosting scene
  81440. * @returns a new skeleton
  81441. */
  81442. Skeleton.Parse = function (parsedSkeleton, scene) {
  81443. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81444. if (parsedSkeleton.dimensionsAtRest) {
  81445. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81446. }
  81447. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81448. var index;
  81449. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81450. var parsedBone = parsedSkeleton.bones[index];
  81451. var parentBone = null;
  81452. if (parsedBone.parentBoneIndex > -1) {
  81453. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81454. }
  81455. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81456. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81457. if (parsedBone.length) {
  81458. bone.length = parsedBone.length;
  81459. }
  81460. if (parsedBone.metadata) {
  81461. bone.metadata = parsedBone.metadata;
  81462. }
  81463. if (parsedBone.animation) {
  81464. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81465. }
  81466. }
  81467. // placed after bones, so createAnimationRange can cascade down
  81468. if (parsedSkeleton.ranges) {
  81469. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81470. var data = parsedSkeleton.ranges[index];
  81471. skeleton.createAnimationRange(data.name, data.from, data.to);
  81472. }
  81473. }
  81474. return skeleton;
  81475. };
  81476. /**
  81477. * Compute all node absolute transforms
  81478. * @param forceUpdate defines if computation must be done even if cache is up to date
  81479. */
  81480. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81481. if (forceUpdate === void 0) { forceUpdate = false; }
  81482. var renderId = this._scene.getRenderId();
  81483. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81484. this.bones[0].computeAbsoluteTransforms();
  81485. this._lastAbsoluteTransformsUpdateId = renderId;
  81486. }
  81487. };
  81488. /**
  81489. * Gets the root pose matrix
  81490. * @returns a matrix
  81491. */
  81492. Skeleton.prototype.getPoseMatrix = function () {
  81493. var poseMatrix = null;
  81494. if (this._meshesWithPoseMatrix.length > 0) {
  81495. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81496. }
  81497. return poseMatrix;
  81498. };
  81499. /**
  81500. * Sorts bones per internal index
  81501. */
  81502. Skeleton.prototype.sortBones = function () {
  81503. var bones = new Array();
  81504. var visited = new Array(this.bones.length);
  81505. for (var index = 0; index < this.bones.length; index++) {
  81506. this._sortBones(index, bones, visited);
  81507. }
  81508. this.bones = bones;
  81509. };
  81510. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81511. if (visited[index]) {
  81512. return;
  81513. }
  81514. visited[index] = true;
  81515. var bone = this.bones[index];
  81516. if (bone._index === undefined) {
  81517. bone._index = index;
  81518. }
  81519. var parentBone = bone.getParent();
  81520. if (parentBone) {
  81521. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81522. }
  81523. bones.push(bone);
  81524. };
  81525. return Skeleton;
  81526. }());
  81527. BABYLON.Skeleton = Skeleton;
  81528. })(BABYLON || (BABYLON = {}));
  81529. //# sourceMappingURL=babylon.skeleton.js.map
  81530. var BABYLON;
  81531. (function (BABYLON) {
  81532. var SphericalPolynomial = /** @class */ (function () {
  81533. function SphericalPolynomial() {
  81534. this.x = BABYLON.Vector3.Zero();
  81535. this.y = BABYLON.Vector3.Zero();
  81536. this.z = BABYLON.Vector3.Zero();
  81537. this.xx = BABYLON.Vector3.Zero();
  81538. this.yy = BABYLON.Vector3.Zero();
  81539. this.zz = BABYLON.Vector3.Zero();
  81540. this.xy = BABYLON.Vector3.Zero();
  81541. this.yz = BABYLON.Vector3.Zero();
  81542. this.zx = BABYLON.Vector3.Zero();
  81543. }
  81544. SphericalPolynomial.prototype.addAmbient = function (color) {
  81545. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81546. this.xx = this.xx.add(colorVector);
  81547. this.yy = this.yy.add(colorVector);
  81548. this.zz = this.zz.add(colorVector);
  81549. };
  81550. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81551. var result = new SphericalPolynomial();
  81552. result.x = harmonics.L11.scale(1.02333);
  81553. result.y = harmonics.L1_1.scale(1.02333);
  81554. result.z = harmonics.L10.scale(1.02333);
  81555. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81556. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81557. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81558. result.yz = harmonics.L2_1.scale(0.858086);
  81559. result.zx = harmonics.L21.scale(0.858086);
  81560. result.xy = harmonics.L2_2.scale(0.858086);
  81561. result.scale(1.0 / Math.PI);
  81562. return result;
  81563. };
  81564. SphericalPolynomial.prototype.scale = function (scale) {
  81565. this.x = this.x.scale(scale);
  81566. this.y = this.y.scale(scale);
  81567. this.z = this.z.scale(scale);
  81568. this.xx = this.xx.scale(scale);
  81569. this.yy = this.yy.scale(scale);
  81570. this.zz = this.zz.scale(scale);
  81571. this.yz = this.yz.scale(scale);
  81572. this.zx = this.zx.scale(scale);
  81573. this.xy = this.xy.scale(scale);
  81574. };
  81575. return SphericalPolynomial;
  81576. }());
  81577. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81578. var SphericalHarmonics = /** @class */ (function () {
  81579. function SphericalHarmonics() {
  81580. this.L00 = BABYLON.Vector3.Zero();
  81581. this.L1_1 = BABYLON.Vector3.Zero();
  81582. this.L10 = BABYLON.Vector3.Zero();
  81583. this.L11 = BABYLON.Vector3.Zero();
  81584. this.L2_2 = BABYLON.Vector3.Zero();
  81585. this.L2_1 = BABYLON.Vector3.Zero();
  81586. this.L20 = BABYLON.Vector3.Zero();
  81587. this.L21 = BABYLON.Vector3.Zero();
  81588. this.L22 = BABYLON.Vector3.Zero();
  81589. }
  81590. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81591. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81592. var c = colorVector.scale(deltaSolidAngle);
  81593. this.L00 = this.L00.add(c.scale(0.282095));
  81594. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81595. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81596. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81597. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81598. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81599. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81600. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81601. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81602. };
  81603. SphericalHarmonics.prototype.scale = function (scale) {
  81604. this.L00 = this.L00.scale(scale);
  81605. this.L1_1 = this.L1_1.scale(scale);
  81606. this.L10 = this.L10.scale(scale);
  81607. this.L11 = this.L11.scale(scale);
  81608. this.L2_2 = this.L2_2.scale(scale);
  81609. this.L2_1 = this.L2_1.scale(scale);
  81610. this.L20 = this.L20.scale(scale);
  81611. this.L21 = this.L21.scale(scale);
  81612. this.L22 = this.L22.scale(scale);
  81613. };
  81614. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81615. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81616. //
  81617. // E_lm = A_l * L_lm
  81618. //
  81619. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81620. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81621. // the scaling factors are given in equation 9.
  81622. // Constant (Band 0)
  81623. this.L00 = this.L00.scale(3.141593);
  81624. // Linear (Band 1)
  81625. this.L1_1 = this.L1_1.scale(2.094395);
  81626. this.L10 = this.L10.scale(2.094395);
  81627. this.L11 = this.L11.scale(2.094395);
  81628. // Quadratic (Band 2)
  81629. this.L2_2 = this.L2_2.scale(0.785398);
  81630. this.L2_1 = this.L2_1.scale(0.785398);
  81631. this.L20 = this.L20.scale(0.785398);
  81632. this.L21 = this.L21.scale(0.785398);
  81633. this.L22 = this.L22.scale(0.785398);
  81634. };
  81635. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81636. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81637. // L = (1/pi) * E * rho
  81638. //
  81639. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81640. this.scale(1.0 / Math.PI);
  81641. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81642. // (The pixel shader must apply albedo after texture fetches, etc).
  81643. };
  81644. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81645. var result = new SphericalHarmonics();
  81646. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81647. result.L1_1 = polynomial.y.scale(0.977204);
  81648. result.L10 = polynomial.z.scale(0.977204);
  81649. result.L11 = polynomial.x.scale(0.977204);
  81650. result.L2_2 = polynomial.xy.scale(1.16538);
  81651. result.L2_1 = polynomial.yz.scale(1.16538);
  81652. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81653. result.L21 = polynomial.zx.scale(1.16538);
  81654. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81655. result.scale(Math.PI);
  81656. return result;
  81657. };
  81658. return SphericalHarmonics;
  81659. }());
  81660. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81661. })(BABYLON || (BABYLON = {}));
  81662. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81663. var BABYLON;
  81664. (function (BABYLON) {
  81665. var FileFaceOrientation = /** @class */ (function () {
  81666. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81667. this.name = name;
  81668. this.worldAxisForNormal = worldAxisForNormal;
  81669. this.worldAxisForFileX = worldAxisForFileX;
  81670. this.worldAxisForFileY = worldAxisForFileY;
  81671. }
  81672. return FileFaceOrientation;
  81673. }());
  81674. ;
  81675. /**
  81676. * Helper class dealing with the extraction of spherical polynomial dataArray
  81677. * from a cube map.
  81678. */
  81679. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81680. function CubeMapToSphericalPolynomialTools() {
  81681. }
  81682. /**
  81683. * Converts a texture to the according Spherical Polynomial data.
  81684. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81685. *
  81686. * @param texture The texture to extract the information from.
  81687. * @return The Spherical Polynomial data.
  81688. */
  81689. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81690. if (!texture.isCube) {
  81691. // Only supports cube Textures currently.
  81692. return null;
  81693. }
  81694. var size = texture.getSize().width;
  81695. var right = texture.readPixels(0);
  81696. var left = texture.readPixels(1);
  81697. var up;
  81698. var down;
  81699. if (texture.isRenderTarget) {
  81700. up = texture.readPixels(3);
  81701. down = texture.readPixels(2);
  81702. }
  81703. else {
  81704. up = texture.readPixels(2);
  81705. down = texture.readPixels(3);
  81706. }
  81707. var front = texture.readPixels(4);
  81708. var back = texture.readPixels(5);
  81709. var gammaSpace = texture.gammaSpace;
  81710. // Always read as RGBA.
  81711. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81712. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81713. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81714. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81715. }
  81716. var cubeInfo = {
  81717. size: size,
  81718. right: right,
  81719. left: left,
  81720. up: up,
  81721. down: down,
  81722. front: front,
  81723. back: back,
  81724. format: format,
  81725. type: type,
  81726. gammaSpace: gammaSpace,
  81727. };
  81728. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81729. };
  81730. /**
  81731. * Converts a cubemap to the according Spherical Polynomial data.
  81732. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81733. *
  81734. * @param cubeInfo The Cube map to extract the information from.
  81735. * @return The Spherical Polynomial data.
  81736. */
  81737. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81738. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81739. var totalSolidAngle = 0.0;
  81740. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81741. var du = 2.0 / cubeInfo.size;
  81742. var dv = du;
  81743. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81744. var minUV = du * 0.5 - 1.0;
  81745. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81746. var fileFace = this.FileFaces[faceIndex];
  81747. var dataArray = cubeInfo[fileFace.name];
  81748. var v = minUV;
  81749. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81750. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81751. // Because SP is still linear, so summation is fine in that basis.
  81752. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81753. for (var y = 0; y < cubeInfo.size; y++) {
  81754. var u = minUV;
  81755. for (var x = 0; x < cubeInfo.size; x++) {
  81756. // World direction (not normalised)
  81757. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81758. worldDirection.normalize();
  81759. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81760. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81761. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81762. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81763. // Handle Integer types.
  81764. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81765. r /= 255;
  81766. g /= 255;
  81767. b /= 255;
  81768. }
  81769. // Handle Gamma space textures.
  81770. if (cubeInfo.gammaSpace) {
  81771. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81772. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81773. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81774. }
  81775. var color = new BABYLON.Color3(r, g, b);
  81776. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81777. totalSolidAngle += deltaSolidAngle;
  81778. u += du;
  81779. }
  81780. v += dv;
  81781. }
  81782. }
  81783. // Solid angle for entire sphere is 4*pi
  81784. var sphereSolidAngle = 4.0 * Math.PI;
  81785. // Adjust the solid angle to allow for how many faces we processed.
  81786. var facesProcessed = 6.0;
  81787. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81788. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81789. // This is needed because the numerical integration over the cube uses a
  81790. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81791. // and also to compensate for accumulative error due to float precision in the summation.
  81792. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81793. sphericalHarmonics.scale(correctionFactor);
  81794. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81795. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81796. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81797. };
  81798. CubeMapToSphericalPolynomialTools.FileFaces = [
  81799. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81800. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81801. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81802. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81803. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81804. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81805. ];
  81806. return CubeMapToSphericalPolynomialTools;
  81807. }());
  81808. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81809. })(BABYLON || (BABYLON = {}));
  81810. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81811. var BABYLON;
  81812. (function (BABYLON) {
  81813. /**
  81814. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81815. */
  81816. var PanoramaToCubeMapTools = /** @class */ (function () {
  81817. function PanoramaToCubeMapTools() {
  81818. }
  81819. /**
  81820. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81821. *
  81822. * @param float32Array The source data.
  81823. * @param inputWidth The width of the input panorama.
  81824. * @param inputhHeight The height of the input panorama.
  81825. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81826. * @return The cubemap data
  81827. */
  81828. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81829. if (!float32Array) {
  81830. throw "ConvertPanoramaToCubemap: input cannot be null";
  81831. }
  81832. if (float32Array.length != inputWidth * inputHeight * 3) {
  81833. throw "ConvertPanoramaToCubemap: input size is wrong";
  81834. }
  81835. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  81836. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  81837. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  81838. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  81839. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  81840. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  81841. return {
  81842. front: textureFront,
  81843. back: textureBack,
  81844. left: textureLeft,
  81845. right: textureRight,
  81846. up: textureUp,
  81847. down: textureDown,
  81848. size: size,
  81849. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  81850. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  81851. gammaSpace: false,
  81852. };
  81853. };
  81854. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  81855. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  81856. var textureArray = new Float32Array(buffer);
  81857. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  81858. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  81859. var dy = 1 / texSize;
  81860. var fy = 0;
  81861. for (var y = 0; y < texSize; y++) {
  81862. var xv1 = faceData[0];
  81863. var xv2 = faceData[2];
  81864. for (var x = 0; x < texSize; x++) {
  81865. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  81866. v.normalize();
  81867. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  81868. // 3 channels per pixels
  81869. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  81870. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  81871. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  81872. xv1 = xv1.add(rotDX1);
  81873. xv2 = xv2.add(rotDX2);
  81874. }
  81875. fy += dy;
  81876. }
  81877. return textureArray;
  81878. };
  81879. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  81880. var theta = Math.atan2(vDir.z, vDir.x);
  81881. var phi = Math.acos(vDir.y);
  81882. while (theta < -Math.PI)
  81883. theta += 2 * Math.PI;
  81884. while (theta > Math.PI)
  81885. theta -= 2 * Math.PI;
  81886. var dx = theta / Math.PI;
  81887. var dy = phi / Math.PI;
  81888. // recenter.
  81889. dx = dx * 0.5 + 0.5;
  81890. var px = Math.round(dx * inputWidth);
  81891. if (px < 0)
  81892. px = 0;
  81893. else if (px >= inputWidth)
  81894. px = inputWidth - 1;
  81895. var py = Math.round(dy * inputHeight);
  81896. if (py < 0)
  81897. py = 0;
  81898. else if (py >= inputHeight)
  81899. py = inputHeight - 1;
  81900. var inputY = (inputHeight - py - 1);
  81901. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  81902. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  81903. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  81904. return {
  81905. r: r,
  81906. g: g,
  81907. b: b
  81908. };
  81909. };
  81910. PanoramaToCubeMapTools.FACE_FRONT = [
  81911. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81912. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81913. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81914. new BABYLON.Vector3(1.0, 1.0, -1.0)
  81915. ];
  81916. PanoramaToCubeMapTools.FACE_BACK = [
  81917. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81918. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81919. new BABYLON.Vector3(1.0, 1.0, 1.0),
  81920. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  81921. ];
  81922. PanoramaToCubeMapTools.FACE_RIGHT = [
  81923. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81924. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81925. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81926. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81927. ];
  81928. PanoramaToCubeMapTools.FACE_LEFT = [
  81929. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81930. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81931. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81932. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  81933. ];
  81934. PanoramaToCubeMapTools.FACE_DOWN = [
  81935. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81936. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81937. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81938. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81939. ];
  81940. PanoramaToCubeMapTools.FACE_UP = [
  81941. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81942. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81943. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81944. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81945. ];
  81946. return PanoramaToCubeMapTools;
  81947. }());
  81948. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81949. })(BABYLON || (BABYLON = {}));
  81950. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81951. var BABYLON;
  81952. (function (BABYLON) {
  81953. ;
  81954. /**
  81955. * This groups tools to convert HDR texture to native colors array.
  81956. */
  81957. var HDRTools = /** @class */ (function () {
  81958. function HDRTools() {
  81959. }
  81960. HDRTools.Ldexp = function (mantissa, exponent) {
  81961. if (exponent > 1023) {
  81962. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81963. }
  81964. if (exponent < -1074) {
  81965. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81966. }
  81967. return mantissa * Math.pow(2, exponent);
  81968. };
  81969. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81970. if (exponent > 0) { /*nonzero pixel*/
  81971. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81972. float32array[index + 0] = red * exponent;
  81973. float32array[index + 1] = green * exponent;
  81974. float32array[index + 2] = blue * exponent;
  81975. }
  81976. else {
  81977. float32array[index + 0] = 0;
  81978. float32array[index + 1] = 0;
  81979. float32array[index + 2] = 0;
  81980. }
  81981. };
  81982. HDRTools.readStringLine = function (uint8array, startIndex) {
  81983. var line = "";
  81984. var character = "";
  81985. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81986. character = String.fromCharCode(uint8array[i]);
  81987. if (character == "\n") {
  81988. break;
  81989. }
  81990. line += character;
  81991. }
  81992. return line;
  81993. };
  81994. /**
  81995. * Reads header information from an RGBE texture stored in a native array.
  81996. * More information on this format are available here:
  81997. * https://en.wikipedia.org/wiki/RGBE_image_format
  81998. *
  81999. * @param uint8array The binary file stored in native array.
  82000. * @return The header information.
  82001. */
  82002. HDRTools.RGBE_ReadHeader = function (uint8array) {
  82003. var height = 0;
  82004. var width = 0;
  82005. var line = this.readStringLine(uint8array, 0);
  82006. if (line[0] != '#' || line[1] != '?') {
  82007. throw "Bad HDR Format.";
  82008. }
  82009. var endOfHeader = false;
  82010. var findFormat = false;
  82011. var lineIndex = 0;
  82012. do {
  82013. lineIndex += (line.length + 1);
  82014. line = this.readStringLine(uint8array, lineIndex);
  82015. if (line == "FORMAT=32-bit_rle_rgbe") {
  82016. findFormat = true;
  82017. }
  82018. else if (line.length == 0) {
  82019. endOfHeader = true;
  82020. }
  82021. } while (!endOfHeader);
  82022. if (!findFormat) {
  82023. throw "HDR Bad header format, unsupported FORMAT";
  82024. }
  82025. lineIndex += (line.length + 1);
  82026. line = this.readStringLine(uint8array, lineIndex);
  82027. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82028. var match = sizeRegexp.exec(line);
  82029. // TODO. Support +Y and -X if needed.
  82030. if (!match || match.length < 3) {
  82031. throw "HDR Bad header format, no size";
  82032. }
  82033. width = parseInt(match[2]);
  82034. height = parseInt(match[1]);
  82035. if (width < 8 || width > 0x7fff) {
  82036. throw "HDR Bad header format, unsupported size";
  82037. }
  82038. lineIndex += (line.length + 1);
  82039. return {
  82040. height: height,
  82041. width: width,
  82042. dataPosition: lineIndex
  82043. };
  82044. };
  82045. /**
  82046. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82047. * This RGBE texture needs to store the information as a panorama.
  82048. *
  82049. * More information on this format are available here:
  82050. * https://en.wikipedia.org/wiki/RGBE_image_format
  82051. *
  82052. * @param buffer The binary file stored in an array buffer.
  82053. * @param size The expected size of the extracted cubemap.
  82054. * @return The Cube Map information.
  82055. */
  82056. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82057. var uint8array = new Uint8Array(buffer);
  82058. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82059. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82060. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82061. return cubeMapData;
  82062. };
  82063. /**
  82064. * Returns the pixels data extracted from an RGBE texture.
  82065. * This pixels will be stored left to right up to down in the R G B order in one array.
  82066. *
  82067. * More information on this format are available here:
  82068. * https://en.wikipedia.org/wiki/RGBE_image_format
  82069. *
  82070. * @param uint8array The binary file stored in an array buffer.
  82071. * @param hdrInfo The header information of the file.
  82072. * @return The pixels data in RGB right to left up to down order.
  82073. */
  82074. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82075. // Keep for multi format supports.
  82076. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82077. };
  82078. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82079. var num_scanlines = hdrInfo.height;
  82080. var scanline_width = hdrInfo.width;
  82081. var a, b, c, d, count;
  82082. var dataIndex = hdrInfo.dataPosition;
  82083. var index = 0, endIndex = 0, i = 0;
  82084. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82085. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82086. // 3 channels of 4 bytes per pixel in float.
  82087. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82088. var resultArray = new Float32Array(resultBuffer);
  82089. // read in each successive scanline
  82090. while (num_scanlines > 0) {
  82091. a = uint8array[dataIndex++];
  82092. b = uint8array[dataIndex++];
  82093. c = uint8array[dataIndex++];
  82094. d = uint8array[dataIndex++];
  82095. if (a != 2 || b != 2 || (c & 0x80)) {
  82096. // this file is not run length encoded
  82097. throw "HDR Bad header format, not RLE";
  82098. }
  82099. if (((c << 8) | d) != scanline_width) {
  82100. throw "HDR Bad header format, wrong scan line width";
  82101. }
  82102. index = 0;
  82103. // read each of the four channels for the scanline into the buffer
  82104. for (i = 0; i < 4; i++) {
  82105. endIndex = (i + 1) * scanline_width;
  82106. while (index < endIndex) {
  82107. a = uint8array[dataIndex++];
  82108. b = uint8array[dataIndex++];
  82109. if (a > 128) {
  82110. // a run of the same value
  82111. count = a - 128;
  82112. if ((count == 0) || (count > endIndex - index)) {
  82113. throw "HDR Bad Format, bad scanline data (run)";
  82114. }
  82115. while (count-- > 0) {
  82116. scanLineArray[index++] = b;
  82117. }
  82118. }
  82119. else {
  82120. // a non-run
  82121. count = a;
  82122. if ((count == 0) || (count > endIndex - index)) {
  82123. throw "HDR Bad Format, bad scanline data (non-run)";
  82124. }
  82125. scanLineArray[index++] = b;
  82126. if (--count > 0) {
  82127. for (var j = 0; j < count; j++) {
  82128. scanLineArray[index++] = uint8array[dataIndex++];
  82129. }
  82130. }
  82131. }
  82132. }
  82133. }
  82134. // now convert data from buffer into floats
  82135. for (i = 0; i < scanline_width; i++) {
  82136. a = scanLineArray[i];
  82137. b = scanLineArray[i + scanline_width];
  82138. c = scanLineArray[i + 2 * scanline_width];
  82139. d = scanLineArray[i + 3 * scanline_width];
  82140. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82141. }
  82142. num_scanlines--;
  82143. }
  82144. return resultArray;
  82145. };
  82146. return HDRTools;
  82147. }());
  82148. BABYLON.HDRTools = HDRTools;
  82149. })(BABYLON || (BABYLON = {}));
  82150. //# sourceMappingURL=babylon.hdr.js.map
  82151. var BABYLON;
  82152. (function (BABYLON) {
  82153. /**
  82154. * Sets of helpers addressing the serialization and deserialization of environment texture
  82155. * stored in a BabylonJS env file.
  82156. * Those files are usually stored as .env files.
  82157. */
  82158. var EnvironmentTextureTools = /** @class */ (function () {
  82159. function EnvironmentTextureTools() {
  82160. }
  82161. /**
  82162. * Gets the environment info from an env file.
  82163. * @param data The array buffer containing the .env bytes.
  82164. * @returns the environment file info (the json header) if successfully parsed.
  82165. */
  82166. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82167. var dataView = new DataView(data);
  82168. var pos = 0;
  82169. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82170. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82171. BABYLON.Tools.Error('Not a babylon environment map');
  82172. return null;
  82173. }
  82174. }
  82175. // Read json manifest - collect characters up to null terminator
  82176. var manifestString = '';
  82177. var charCode = 0x00;
  82178. while ((charCode = dataView.getUint8(pos++))) {
  82179. manifestString += String.fromCharCode(charCode);
  82180. }
  82181. var manifest = JSON.parse(manifestString);
  82182. if (manifest.specular) {
  82183. // Extend the header with the position of the payload.
  82184. manifest.specular.specularDataPosition = pos;
  82185. }
  82186. return manifest;
  82187. };
  82188. /**
  82189. * Creates an environment texture from a loaded cube texture.
  82190. * @param texture defines the cube texture to convert in env file
  82191. * @return a promise containing the environment data if succesfull.
  82192. */
  82193. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82194. var _this = this;
  82195. var internalTexture = texture.getInternalTexture();
  82196. if (!internalTexture) {
  82197. return Promise.reject("The cube texture is invalid.");
  82198. }
  82199. if (!texture._prefiltered) {
  82200. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82201. }
  82202. var engine = internalTexture.getEngine();
  82203. if (engine && engine.premultipliedAlpha) {
  82204. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82205. }
  82206. var canvas = engine.getRenderingCanvas();
  82207. if (!canvas) {
  82208. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82209. }
  82210. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82211. if (!engine.getCaps().textureFloatRender) {
  82212. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82213. if (!engine.getCaps().textureHalfFloatRender) {
  82214. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82215. }
  82216. }
  82217. var cubeWidth = internalTexture.width;
  82218. var hostingScene = new BABYLON.Scene(engine);
  82219. var specularTextures = {};
  82220. var promises = [];
  82221. // Read and collect all mipmaps data from the cube.
  82222. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82223. mipmapsCount = Math.round(mipmapsCount);
  82224. var _loop_1 = function (i) {
  82225. var faceWidth = Math.pow(2, mipmapsCount - i);
  82226. var _loop_2 = function (face) {
  82227. var data = texture.readPixels(face, i);
  82228. // Creates a temp texture with the face data.
  82229. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82230. // And rgbdEncode them.
  82231. var promise = new Promise(function (resolve, reject) {
  82232. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  82233. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82234. rgbdPostProcess.onApply = function (effect) {
  82235. effect._bindTexture("textureSampler", tempTexture);
  82236. };
  82237. // As the process needs to happen on the main canvas, keep track of the current size
  82238. var currentW = engine.getRenderWidth();
  82239. var currentH = engine.getRenderHeight();
  82240. // Set the desired size for the texture
  82241. engine.setSize(faceWidth, faceWidth);
  82242. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82243. // Reading datas from WebGL
  82244. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82245. var fileReader = new FileReader();
  82246. fileReader.onload = function (event) {
  82247. var arrayBuffer = event.target.result;
  82248. specularTextures[i * 6 + face] = arrayBuffer;
  82249. resolve();
  82250. };
  82251. fileReader.readAsArrayBuffer(blob);
  82252. });
  82253. // Reapply the previous canvas size
  82254. engine.setSize(currentW, currentH);
  82255. });
  82256. });
  82257. promises.push(promise);
  82258. };
  82259. // All faces of the cube.
  82260. for (var face = 0; face < 6; face++) {
  82261. _loop_2(face);
  82262. }
  82263. };
  82264. for (var i = 0; i <= mipmapsCount; i++) {
  82265. _loop_1(i);
  82266. }
  82267. // Once all the textures haves been collected as RGBD stored in PNGs
  82268. return Promise.all(promises).then(function () {
  82269. // We can delete the hosting scene keeping track of all the creation objects
  82270. hostingScene.dispose();
  82271. // Creates the json header for the env texture
  82272. var info = {
  82273. version: 1,
  82274. width: cubeWidth,
  82275. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82276. specular: {
  82277. mipmaps: []
  82278. }
  82279. };
  82280. // Sets the specular image data information
  82281. var position = 0;
  82282. for (var i = 0; i <= mipmapsCount; i++) {
  82283. for (var face = 0; face < 6; face++) {
  82284. var byteLength = specularTextures[i * 6 + face].byteLength;
  82285. info.specular.mipmaps.push({
  82286. length: byteLength,
  82287. position: position
  82288. });
  82289. position += byteLength;
  82290. }
  82291. }
  82292. // Encode the JSON as an array buffer
  82293. var infoString = JSON.stringify(info);
  82294. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82295. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82296. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82297. infoView[i] = infoString.charCodeAt(i);
  82298. }
  82299. // Ends up with a null terminator for easier parsing
  82300. infoView[infoString.length] = 0x00;
  82301. // Computes the final required size and creates the storage
  82302. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82303. var finalBuffer = new ArrayBuffer(totalSize);
  82304. var finalBufferView = new Uint8Array(finalBuffer);
  82305. var dataView = new DataView(finalBuffer);
  82306. // Copy the magic bytes identifying the file in
  82307. var pos = 0;
  82308. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82309. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82310. }
  82311. // Add the json info
  82312. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82313. pos += infoBuffer.byteLength;
  82314. // Finally inserts the texture data
  82315. for (var i = 0; i <= mipmapsCount; i++) {
  82316. for (var face = 0; face < 6; face++) {
  82317. var dataBuffer = specularTextures[i * 6 + face];
  82318. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82319. pos += dataBuffer.byteLength;
  82320. }
  82321. }
  82322. // Voila
  82323. return finalBuffer;
  82324. });
  82325. };
  82326. /**
  82327. * Creates a JSON representation of the spherical data.
  82328. * @param texture defines the texture containing the polynomials
  82329. * @return the JSON representation of the spherical info
  82330. */
  82331. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82332. var polynmials = texture.sphericalPolynomial;
  82333. if (polynmials == null) {
  82334. return null;
  82335. }
  82336. return {
  82337. polynomials: true,
  82338. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82339. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82340. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82341. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82342. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82343. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82344. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82345. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82346. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82347. };
  82348. };
  82349. /**
  82350. * Uploads the texture info contained in the env file to te GPU.
  82351. * @param texture defines the internal texture to upload to
  82352. * @param arrayBuffer defines the buffer cotaining the data to load
  82353. * @param info defines the texture info retrieved through the GetEnvInfo method
  82354. * @returns a promise
  82355. */
  82356. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  82357. if (info.version !== 1) {
  82358. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82359. }
  82360. var specularInfo = info.specular;
  82361. if (!specularInfo) {
  82362. // Nothing else parsed so far
  82363. return Promise.resolve();
  82364. }
  82365. // Double checks the enclosed info
  82366. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82367. mipmapsCount = Math.round(mipmapsCount) + 1;
  82368. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82369. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82370. }
  82371. // Gets everything ready.
  82372. var engine = texture.getEngine();
  82373. var expandTexture = false;
  82374. var generateNonLODTextures = false;
  82375. var rgbdPostProcess = null;
  82376. var cubeRtt = null;
  82377. var lodTextures = null;
  82378. var caps = engine.getCaps();
  82379. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82380. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82381. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82382. // Add extra process if texture lod is not supported
  82383. if (!caps.textureLOD) {
  82384. expandTexture = false;
  82385. generateNonLODTextures = true;
  82386. lodTextures = {};
  82387. }
  82388. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82389. else if (engine.webGLVersion < 2) {
  82390. expandTexture = false;
  82391. }
  82392. // If half float available we can uncompress the texture
  82393. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82394. expandTexture = true;
  82395. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82396. }
  82397. // If full float available we can uncompress the texture
  82398. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82399. expandTexture = true;
  82400. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82401. }
  82402. // Expand the texture if possible
  82403. if (expandTexture) {
  82404. // Simply run through the decode PP
  82405. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82406. texture._isRGBD = false;
  82407. texture.invertY = false;
  82408. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82409. generateDepthBuffer: false,
  82410. generateMipMaps: true,
  82411. generateStencilBuffer: false,
  82412. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82413. type: texture.type,
  82414. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82415. });
  82416. }
  82417. else {
  82418. texture._isRGBD = true;
  82419. texture.invertY = true;
  82420. // In case of missing support, applies the same patch than DDS files.
  82421. if (generateNonLODTextures) {
  82422. var mipSlices = 3;
  82423. var scale = texture._lodGenerationScale;
  82424. var offset = texture._lodGenerationOffset;
  82425. for (var i = 0; i < mipSlices; i++) {
  82426. //compute LOD from even spacing in smoothness (matching shader calculation)
  82427. var smoothness = i / (mipSlices - 1);
  82428. var roughness = 1 - smoothness;
  82429. var minLODIndex = offset; // roughness = 0
  82430. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  82431. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82432. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82433. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82434. glTextureFromLod.isCube = true;
  82435. glTextureFromLod.invertY = true;
  82436. glTextureFromLod.generateMipMaps = false;
  82437. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82438. // Wrap in a base texture for easy binding.
  82439. var lodTexture = new BABYLON.BaseTexture(null);
  82440. lodTexture.isCube = true;
  82441. lodTexture._texture = glTextureFromLod;
  82442. lodTextures[mipmapIndex] = lodTexture;
  82443. switch (i) {
  82444. case 0:
  82445. texture._lodTextureLow = lodTexture;
  82446. break;
  82447. case 1:
  82448. texture._lodTextureMid = lodTexture;
  82449. break;
  82450. case 2:
  82451. texture._lodTextureHigh = lodTexture;
  82452. break;
  82453. }
  82454. }
  82455. }
  82456. }
  82457. var promises = [];
  82458. var _loop_3 = function (i) {
  82459. var _loop_4 = function (face) {
  82460. // Retrieves the face data
  82461. var imageData = specularInfo.mipmaps[i * 6 + face];
  82462. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  82463. // Constructs an image element from bytes
  82464. var blob = new Blob([bytes], { type: 'image/png' });
  82465. var url = URL.createObjectURL(blob);
  82466. var image = new Image();
  82467. image.src = url;
  82468. // Enqueue promise to upload to the texture.
  82469. var promise = new Promise(function (resolve, reject) {
  82470. ;
  82471. image.onload = function () {
  82472. if (expandTexture) {
  82473. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82474. reject(message);
  82475. }, image);
  82476. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82477. // Uncompress the data to a RTT
  82478. rgbdPostProcess.onApply = function (effect) {
  82479. effect._bindTexture("textureSampler", tempTexture_1);
  82480. effect.setFloat2("scale", 1, 1);
  82481. };
  82482. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82483. // Cleanup
  82484. engine.restoreDefaultFramebuffer();
  82485. tempTexture_1.dispose();
  82486. window.URL.revokeObjectURL(url);
  82487. resolve();
  82488. });
  82489. }
  82490. else {
  82491. engine._uploadImageToTexture(texture, face, i, image);
  82492. // Upload the face to the none lod texture support
  82493. if (generateNonLODTextures) {
  82494. var lodTexture = lodTextures[i];
  82495. if (lodTexture) {
  82496. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82497. }
  82498. }
  82499. resolve();
  82500. }
  82501. };
  82502. image.onerror = function (error) {
  82503. reject(error);
  82504. };
  82505. });
  82506. promises.push(promise);
  82507. };
  82508. // All faces
  82509. for (var face = 0; face < 6; face++) {
  82510. _loop_4(face);
  82511. }
  82512. };
  82513. // All mipmaps
  82514. for (var i = 0; i < mipmapsCount; i++) {
  82515. _loop_3(i);
  82516. }
  82517. // Once all done, finishes the cleanup and return
  82518. return Promise.all(promises).then(function () {
  82519. // Relase temp RTT.
  82520. if (cubeRtt) {
  82521. engine._releaseFramebufferObjects(cubeRtt);
  82522. cubeRtt._swapAndDie(texture);
  82523. }
  82524. // Relase temp Post Process.
  82525. if (rgbdPostProcess) {
  82526. rgbdPostProcess.dispose();
  82527. }
  82528. // Flag internal texture as ready in case they are in use.
  82529. if (generateNonLODTextures) {
  82530. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82531. texture._lodTextureHigh._texture.isReady = true;
  82532. }
  82533. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82534. texture._lodTextureMid._texture.isReady = true;
  82535. }
  82536. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82537. texture._lodTextureLow._texture.isReady = true;
  82538. }
  82539. }
  82540. });
  82541. };
  82542. /**
  82543. * Uploads spherical polynomials information to the texture.
  82544. * @param texture defines the texture we are trying to upload the information to
  82545. * @param arrayBuffer defines the array buffer holding the data
  82546. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82547. */
  82548. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82549. if (info.version !== 1) {
  82550. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82551. }
  82552. var irradianceInfo = info.irradiance;
  82553. if (!irradianceInfo) {
  82554. return;
  82555. }
  82556. //harmonics now represent radiance
  82557. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82558. if (irradianceInfo.polynomials) {
  82559. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82560. }
  82561. else {
  82562. // convert From SH to SP.
  82563. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82564. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82565. }
  82566. };
  82567. /**
  82568. * Upload spherical polynomial coefficients to the texture
  82569. * @param polynmials Spherical polynmial coefficients (9)
  82570. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82571. */
  82572. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82573. outPolynomialCoefficents.x.x = polynmials.x[0];
  82574. outPolynomialCoefficents.x.y = polynmials.x[1];
  82575. outPolynomialCoefficents.x.z = polynmials.x[2];
  82576. outPolynomialCoefficents.y.x = polynmials.y[0];
  82577. outPolynomialCoefficents.y.y = polynmials.y[1];
  82578. outPolynomialCoefficents.y.z = polynmials.y[2];
  82579. outPolynomialCoefficents.z.x = polynmials.z[0];
  82580. outPolynomialCoefficents.z.y = polynmials.z[1];
  82581. outPolynomialCoefficents.z.z = polynmials.z[2];
  82582. //xx
  82583. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82584. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82585. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82586. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82587. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82588. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82589. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82590. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82591. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82592. //yz
  82593. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82594. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82595. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82596. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82597. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82598. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82599. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82600. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82601. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82602. };
  82603. /**
  82604. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82605. * L = (1/pi) * E * rho
  82606. *
  82607. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82608. * @param harmonics Spherical harmonic coefficients (9)
  82609. */
  82610. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82611. var scaleFactor = 1 / Math.PI;
  82612. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82613. // (The pixel shader must apply albedo after texture fetches, etc).
  82614. harmonics.l00[0] *= scaleFactor;
  82615. harmonics.l00[1] *= scaleFactor;
  82616. harmonics.l00[2] *= scaleFactor;
  82617. harmonics.l1_1[0] *= scaleFactor;
  82618. harmonics.l1_1[1] *= scaleFactor;
  82619. harmonics.l1_1[2] *= scaleFactor;
  82620. harmonics.l10[0] *= scaleFactor;
  82621. harmonics.l10[1] *= scaleFactor;
  82622. harmonics.l10[2] *= scaleFactor;
  82623. harmonics.l11[0] *= scaleFactor;
  82624. harmonics.l11[1] *= scaleFactor;
  82625. harmonics.l11[2] *= scaleFactor;
  82626. harmonics.l2_2[0] *= scaleFactor;
  82627. harmonics.l2_2[1] *= scaleFactor;
  82628. harmonics.l2_2[2] *= scaleFactor;
  82629. harmonics.l2_1[0] *= scaleFactor;
  82630. harmonics.l2_1[1] *= scaleFactor;
  82631. harmonics.l2_1[2] *= scaleFactor;
  82632. harmonics.l20[0] *= scaleFactor;
  82633. harmonics.l20[1] *= scaleFactor;
  82634. harmonics.l20[2] *= scaleFactor;
  82635. harmonics.l21[0] *= scaleFactor;
  82636. harmonics.l21[1] *= scaleFactor;
  82637. harmonics.l21[2] *= scaleFactor;
  82638. harmonics.l22[0] *= scaleFactor;
  82639. harmonics.l22[1] *= scaleFactor;
  82640. harmonics.l22[2] *= scaleFactor;
  82641. };
  82642. /**
  82643. * Convert spherical harmonics to spherical polynomial coefficients
  82644. * @param harmonics Spherical harmonic coefficients (9)
  82645. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82646. */
  82647. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82648. var rPi = 1 / Math.PI;
  82649. //x
  82650. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82651. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82652. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82653. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82654. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82655. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82656. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82657. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82658. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82659. //xx
  82660. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82661. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82662. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82663. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82664. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82665. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82666. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82667. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82668. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82669. //yz
  82670. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82671. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82672. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82673. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82674. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82675. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82676. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82677. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82678. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82679. };
  82680. /**
  82681. * Magic number identifying the env file.
  82682. */
  82683. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82684. return EnvironmentTextureTools;
  82685. }());
  82686. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82687. })(BABYLON || (BABYLON = {}));
  82688. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82689. var BABYLON;
  82690. (function (BABYLON) {
  82691. /**
  82692. * This represents a texture coming from an HDR input.
  82693. *
  82694. * The only supported format is currently panorama picture stored in RGBE format.
  82695. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82696. */
  82697. var HDRCubeTexture = /** @class */ (function (_super) {
  82698. __extends(HDRCubeTexture, _super);
  82699. /**
  82700. * Instantiates an HDRTexture from the following parameters.
  82701. *
  82702. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82703. * @param scene The scene the texture will be used in
  82704. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82705. * @param noMipmap Forces to not generate the mipmap if true
  82706. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82707. * @param gammaSpace 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)
  82708. * @param reserved Reserved flag for internal use.
  82709. */
  82710. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82711. if (noMipmap === void 0) { noMipmap = false; }
  82712. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82713. if (gammaSpace === void 0) { gammaSpace = false; }
  82714. if (reserved === void 0) { reserved = false; }
  82715. if (onLoad === void 0) { onLoad = null; }
  82716. if (onError === void 0) { onError = null; }
  82717. var _this = _super.call(this, scene) || this;
  82718. _this._generateHarmonics = true;
  82719. _this._onLoad = null;
  82720. _this._onError = null;
  82721. /**
  82722. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82723. */
  82724. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82725. _this._isBlocking = true;
  82726. _this._rotationY = 0;
  82727. /**
  82728. * Gets or sets the center of the bounding box associated with the cube texture
  82729. * It must define where the camera used to render the texture was set
  82730. */
  82731. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82732. if (!url) {
  82733. return _this;
  82734. }
  82735. _this.name = url;
  82736. _this.url = url;
  82737. _this.hasAlpha = false;
  82738. _this.isCube = true;
  82739. _this._textureMatrix = BABYLON.Matrix.Identity();
  82740. _this._onLoad = onLoad;
  82741. _this._onError = onError;
  82742. _this.gammaSpace = gammaSpace;
  82743. _this._noMipmap = noMipmap;
  82744. _this._size = size;
  82745. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82746. if (!_this._texture) {
  82747. if (!scene.useDelayedTextureLoading) {
  82748. _this.loadTexture();
  82749. }
  82750. else {
  82751. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82752. }
  82753. }
  82754. return _this;
  82755. }
  82756. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82757. /**
  82758. * Gets wether or not the texture is blocking during loading.
  82759. */
  82760. get: function () {
  82761. return this._isBlocking;
  82762. },
  82763. /**
  82764. * Sets wether or not the texture is blocking during loading.
  82765. */
  82766. set: function (value) {
  82767. this._isBlocking = value;
  82768. },
  82769. enumerable: true,
  82770. configurable: true
  82771. });
  82772. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82773. /**
  82774. * Gets texture matrix rotation angle around Y axis radians.
  82775. */
  82776. get: function () {
  82777. return this._rotationY;
  82778. },
  82779. /**
  82780. * Sets texture matrix rotation angle around Y axis in radians.
  82781. */
  82782. set: function (value) {
  82783. this._rotationY = value;
  82784. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82785. },
  82786. enumerable: true,
  82787. configurable: true
  82788. });
  82789. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82790. get: function () {
  82791. return this._boundingBoxSize;
  82792. },
  82793. /**
  82794. * Gets or sets the size of the bounding box associated with the cube texture
  82795. * When defined, the cubemap will switch to local mode
  82796. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82797. * @example https://www.babylonjs-playground.com/#RNASML
  82798. */
  82799. set: function (value) {
  82800. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82801. return;
  82802. }
  82803. this._boundingBoxSize = value;
  82804. var scene = this.getScene();
  82805. if (scene) {
  82806. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82807. }
  82808. },
  82809. enumerable: true,
  82810. configurable: true
  82811. });
  82812. /**
  82813. * Occurs when the file is raw .hdr file.
  82814. */
  82815. HDRCubeTexture.prototype.loadTexture = function () {
  82816. var _this = this;
  82817. var callback = function (buffer) {
  82818. _this.lodGenerationOffset = 0.0;
  82819. _this.lodGenerationScale = 0.8;
  82820. var scene = _this.getScene();
  82821. if (!scene) {
  82822. return null;
  82823. }
  82824. // Extract the raw linear data.
  82825. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82826. // Generate harmonics if needed.
  82827. if (_this._generateHarmonics) {
  82828. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82829. _this.sphericalPolynomial = sphericalPolynomial;
  82830. }
  82831. var results = [];
  82832. var byteArray = null;
  82833. // Push each faces.
  82834. for (var j = 0; j < 6; j++) {
  82835. // Create uintarray fallback.
  82836. if (!scene.getEngine().getCaps().textureFloat) {
  82837. // 3 channels of 1 bytes per pixel in bytes.
  82838. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  82839. byteArray = new Uint8Array(byteBuffer);
  82840. }
  82841. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  82842. // If special cases.
  82843. if (_this.gammaSpace || byteArray) {
  82844. for (var i = 0; i < _this._size * _this._size; i++) {
  82845. // Put in gamma space if requested.
  82846. if (_this.gammaSpace) {
  82847. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  82848. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  82849. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  82850. }
  82851. // Convert to int texture for fallback.
  82852. if (byteArray) {
  82853. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  82854. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  82855. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  82856. // May use luminance instead if the result is not accurate.
  82857. var max = Math.max(Math.max(r, g), b);
  82858. if (max > 255) {
  82859. var scale = 255 / max;
  82860. r *= scale;
  82861. g *= scale;
  82862. b *= scale;
  82863. }
  82864. byteArray[(i * 3) + 0] = r;
  82865. byteArray[(i * 3) + 1] = g;
  82866. byteArray[(i * 3) + 2] = b;
  82867. }
  82868. }
  82869. }
  82870. if (byteArray) {
  82871. results.push(byteArray);
  82872. }
  82873. else {
  82874. results.push(dataFace);
  82875. }
  82876. }
  82877. return results;
  82878. };
  82879. var scene = this.getScene();
  82880. if (scene) {
  82881. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  82882. }
  82883. };
  82884. HDRCubeTexture.prototype.clone = function () {
  82885. var scene = this.getScene();
  82886. if (!scene) {
  82887. return this;
  82888. }
  82889. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  82890. // Base texture
  82891. newTexture.level = this.level;
  82892. newTexture.wrapU = this.wrapU;
  82893. newTexture.wrapV = this.wrapV;
  82894. newTexture.coordinatesIndex = this.coordinatesIndex;
  82895. newTexture.coordinatesMode = this.coordinatesMode;
  82896. return newTexture;
  82897. };
  82898. // Methods
  82899. HDRCubeTexture.prototype.delayLoad = function () {
  82900. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82901. return;
  82902. }
  82903. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82904. this._texture = this._getFromCache(this.url, this._noMipmap);
  82905. if (!this._texture) {
  82906. this.loadTexture();
  82907. }
  82908. };
  82909. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  82910. return this._textureMatrix;
  82911. };
  82912. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  82913. this._textureMatrix = value;
  82914. };
  82915. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82916. var texture = null;
  82917. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82918. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  82919. texture.name = parsedTexture.name;
  82920. texture.hasAlpha = parsedTexture.hasAlpha;
  82921. texture.level = parsedTexture.level;
  82922. texture.coordinatesMode = parsedTexture.coordinatesMode;
  82923. texture.isBlocking = parsedTexture.isBlocking;
  82924. }
  82925. if (texture) {
  82926. if (parsedTexture.boundingBoxPosition) {
  82927. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  82928. }
  82929. if (parsedTexture.boundingBoxSize) {
  82930. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  82931. }
  82932. if (parsedTexture.rotationY) {
  82933. texture.rotationY = parsedTexture.rotationY;
  82934. }
  82935. }
  82936. return texture;
  82937. };
  82938. HDRCubeTexture.prototype.serialize = function () {
  82939. if (!this.name) {
  82940. return null;
  82941. }
  82942. var serializationObject = {};
  82943. serializationObject.name = this.name;
  82944. serializationObject.hasAlpha = this.hasAlpha;
  82945. serializationObject.isCube = true;
  82946. serializationObject.level = this.level;
  82947. serializationObject.size = this._size;
  82948. serializationObject.coordinatesMode = this.coordinatesMode;
  82949. serializationObject.useInGammaSpace = this.gammaSpace;
  82950. serializationObject.generateHarmonics = this._generateHarmonics;
  82951. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82952. serializationObject.noMipmap = this._noMipmap;
  82953. serializationObject.isBlocking = this._isBlocking;
  82954. serializationObject.rotationY = this._rotationY;
  82955. return serializationObject;
  82956. };
  82957. HDRCubeTexture._facesMapping = [
  82958. "right",
  82959. "left",
  82960. "up",
  82961. "down",
  82962. "front",
  82963. "back"
  82964. ];
  82965. return HDRCubeTexture;
  82966. }(BABYLON.BaseTexture));
  82967. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82968. })(BABYLON || (BABYLON = {}));
  82969. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82970. var BABYLON;
  82971. (function (BABYLON) {
  82972. var IndexedVector2 = /** @class */ (function (_super) {
  82973. __extends(IndexedVector2, _super);
  82974. function IndexedVector2(original, index) {
  82975. var _this = _super.call(this, original.x, original.y) || this;
  82976. _this.index = index;
  82977. return _this;
  82978. }
  82979. return IndexedVector2;
  82980. }(BABYLON.Vector2));
  82981. var PolygonPoints = /** @class */ (function () {
  82982. function PolygonPoints() {
  82983. this.elements = new Array();
  82984. }
  82985. PolygonPoints.prototype.add = function (originalPoints) {
  82986. var _this = this;
  82987. var result = new Array();
  82988. originalPoints.forEach(function (point) {
  82989. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82990. var newPoint = new IndexedVector2(point, _this.elements.length);
  82991. result.push(newPoint);
  82992. _this.elements.push(newPoint);
  82993. }
  82994. });
  82995. return result;
  82996. };
  82997. PolygonPoints.prototype.computeBounds = function () {
  82998. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82999. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83000. this.elements.forEach(function (point) {
  83001. // x
  83002. if (point.x < lmin.x) {
  83003. lmin.x = point.x;
  83004. }
  83005. else if (point.x > lmax.x) {
  83006. lmax.x = point.x;
  83007. }
  83008. // y
  83009. if (point.y < lmin.y) {
  83010. lmin.y = point.y;
  83011. }
  83012. else if (point.y > lmax.y) {
  83013. lmax.y = point.y;
  83014. }
  83015. });
  83016. return {
  83017. min: lmin,
  83018. max: lmax,
  83019. width: lmax.x - lmin.x,
  83020. height: lmax.y - lmin.y
  83021. };
  83022. };
  83023. return PolygonPoints;
  83024. }());
  83025. var Polygon = /** @class */ (function () {
  83026. function Polygon() {
  83027. }
  83028. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83029. return [
  83030. new BABYLON.Vector2(xmin, ymin),
  83031. new BABYLON.Vector2(xmax, ymin),
  83032. new BABYLON.Vector2(xmax, ymax),
  83033. new BABYLON.Vector2(xmin, ymax)
  83034. ];
  83035. };
  83036. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83037. if (cx === void 0) { cx = 0; }
  83038. if (cy === void 0) { cy = 0; }
  83039. if (numberOfSides === void 0) { numberOfSides = 32; }
  83040. var result = new Array();
  83041. var angle = 0;
  83042. var increment = (Math.PI * 2) / numberOfSides;
  83043. for (var i = 0; i < numberOfSides; i++) {
  83044. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83045. angle -= increment;
  83046. }
  83047. return result;
  83048. };
  83049. Polygon.Parse = function (input) {
  83050. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83051. var i, result = [];
  83052. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83053. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83054. }
  83055. return result;
  83056. };
  83057. Polygon.StartingAt = function (x, y) {
  83058. return BABYLON.Path2.StartingAt(x, y);
  83059. };
  83060. return Polygon;
  83061. }());
  83062. BABYLON.Polygon = Polygon;
  83063. var PolygonMeshBuilder = /** @class */ (function () {
  83064. function PolygonMeshBuilder(name, contours, scene) {
  83065. this._points = new PolygonPoints();
  83066. this._outlinepoints = new PolygonPoints();
  83067. this._holes = new Array();
  83068. this._epoints = new Array();
  83069. this._eholes = new Array();
  83070. this._name = name;
  83071. this._scene = scene;
  83072. var points;
  83073. if (contours instanceof BABYLON.Path2) {
  83074. points = contours.getPoints();
  83075. }
  83076. else {
  83077. points = contours;
  83078. }
  83079. this._addToepoint(points);
  83080. this._points.add(points);
  83081. this._outlinepoints.add(points);
  83082. if (typeof earcut === 'undefined') {
  83083. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83084. }
  83085. }
  83086. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83087. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83088. var p = points_1[_i];
  83089. this._epoints.push(p.x, p.y);
  83090. }
  83091. };
  83092. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83093. this._points.add(hole);
  83094. var holepoints = new PolygonPoints();
  83095. holepoints.add(hole);
  83096. this._holes.push(holepoints);
  83097. this._eholes.push(this._epoints.length / 2);
  83098. this._addToepoint(hole);
  83099. return this;
  83100. };
  83101. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83102. var _this = this;
  83103. if (updatable === void 0) { updatable = false; }
  83104. if (depth === void 0) { depth = 0; }
  83105. var result = new BABYLON.Mesh(this._name, this._scene);
  83106. var normals = new Array();
  83107. var positions = new Array();
  83108. var uvs = new Array();
  83109. var bounds = this._points.computeBounds();
  83110. this._points.elements.forEach(function (p) {
  83111. normals.push(0, 1.0, 0);
  83112. positions.push(p.x, 0, p.y);
  83113. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83114. });
  83115. var indices = new Array();
  83116. var res = earcut(this._epoints, this._eholes, 2);
  83117. for (var i = 0; i < res.length; i++) {
  83118. indices.push(res[i]);
  83119. }
  83120. if (depth > 0) {
  83121. var positionscount = (positions.length / 3); //get the current pointcount
  83122. this._points.elements.forEach(function (p) {
  83123. normals.push(0, -1.0, 0);
  83124. positions.push(p.x, -depth, p.y);
  83125. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83126. });
  83127. var totalCount = indices.length;
  83128. for (var i = 0; i < totalCount; i += 3) {
  83129. var i0 = indices[i + 0];
  83130. var i1 = indices[i + 1];
  83131. var i2 = indices[i + 2];
  83132. indices.push(i2 + positionscount);
  83133. indices.push(i1 + positionscount);
  83134. indices.push(i0 + positionscount);
  83135. }
  83136. //Add the sides
  83137. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83138. this._holes.forEach(function (hole) {
  83139. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83140. });
  83141. }
  83142. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83143. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83144. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83145. result.setIndices(indices);
  83146. return result;
  83147. };
  83148. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83149. var StartIndex = positions.length / 3;
  83150. var ulength = 0;
  83151. for (var i = 0; i < points.elements.length; i++) {
  83152. var p = points.elements[i];
  83153. var p1;
  83154. if ((i + 1) > points.elements.length - 1) {
  83155. p1 = points.elements[0];
  83156. }
  83157. else {
  83158. p1 = points.elements[i + 1];
  83159. }
  83160. positions.push(p.x, 0, p.y);
  83161. positions.push(p.x, -depth, p.y);
  83162. positions.push(p1.x, 0, p1.y);
  83163. positions.push(p1.x, -depth, p1.y);
  83164. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83165. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83166. var v3 = v2.subtract(v1);
  83167. var v4 = new BABYLON.Vector3(0, 1, 0);
  83168. var vn = BABYLON.Vector3.Cross(v3, v4);
  83169. vn = vn.normalize();
  83170. uvs.push(ulength / bounds.width, 0);
  83171. uvs.push(ulength / bounds.width, 1);
  83172. ulength += v3.length();
  83173. uvs.push((ulength / bounds.width), 0);
  83174. uvs.push((ulength / bounds.width), 1);
  83175. if (!flip) {
  83176. normals.push(-vn.x, -vn.y, -vn.z);
  83177. normals.push(-vn.x, -vn.y, -vn.z);
  83178. normals.push(-vn.x, -vn.y, -vn.z);
  83179. normals.push(-vn.x, -vn.y, -vn.z);
  83180. indices.push(StartIndex);
  83181. indices.push(StartIndex + 1);
  83182. indices.push(StartIndex + 2);
  83183. indices.push(StartIndex + 1);
  83184. indices.push(StartIndex + 3);
  83185. indices.push(StartIndex + 2);
  83186. }
  83187. else {
  83188. normals.push(vn.x, vn.y, vn.z);
  83189. normals.push(vn.x, vn.y, vn.z);
  83190. normals.push(vn.x, vn.y, vn.z);
  83191. normals.push(vn.x, vn.y, vn.z);
  83192. indices.push(StartIndex);
  83193. indices.push(StartIndex + 2);
  83194. indices.push(StartIndex + 1);
  83195. indices.push(StartIndex + 1);
  83196. indices.push(StartIndex + 2);
  83197. indices.push(StartIndex + 3);
  83198. }
  83199. StartIndex += 4;
  83200. }
  83201. ;
  83202. };
  83203. return PolygonMeshBuilder;
  83204. }());
  83205. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83206. })(BABYLON || (BABYLON = {}));
  83207. //# sourceMappingURL=babylon.polygonMesh.js.map
  83208. var BABYLON;
  83209. (function (BABYLON) {
  83210. // Unique ID when we import meshes from Babylon to CSG
  83211. var currentCSGMeshId = 0;
  83212. // # class Vertex
  83213. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83214. // one to provide additional features like texture coordinates and vertex
  83215. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83216. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83217. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83218. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83219. // is not used anywhere else.
  83220. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83221. var Vertex = /** @class */ (function () {
  83222. function Vertex(pos, normal, uv) {
  83223. this.pos = pos;
  83224. this.normal = normal;
  83225. this.uv = uv;
  83226. }
  83227. Vertex.prototype.clone = function () {
  83228. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83229. };
  83230. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83231. // orientation of a polygon is flipped.
  83232. Vertex.prototype.flip = function () {
  83233. this.normal = this.normal.scale(-1);
  83234. };
  83235. // Create a new vertex between this vertex and `other` by linearly
  83236. // interpolating all properties using a parameter of `t`. Subclasses should
  83237. // override this to interpolate additional properties.
  83238. Vertex.prototype.interpolate = function (other, t) {
  83239. 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));
  83240. };
  83241. return Vertex;
  83242. }());
  83243. // # class Plane
  83244. // Represents a plane in 3D space.
  83245. var Plane = /** @class */ (function () {
  83246. function Plane(normal, w) {
  83247. this.normal = normal;
  83248. this.w = w;
  83249. }
  83250. Plane.FromPoints = function (a, b, c) {
  83251. var v0 = c.subtract(a);
  83252. var v1 = b.subtract(a);
  83253. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83254. return null;
  83255. }
  83256. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83257. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83258. };
  83259. Plane.prototype.clone = function () {
  83260. return new Plane(this.normal.clone(), this.w);
  83261. };
  83262. Plane.prototype.flip = function () {
  83263. this.normal.scaleInPlace(-1);
  83264. this.w = -this.w;
  83265. };
  83266. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83267. // fragments in the appropriate lists. Coplanar polygons go into either
  83268. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83269. // respect to this plane. Polygons in front or in back of this plane go into
  83270. // either `front` or `back`.
  83271. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83272. var COPLANAR = 0;
  83273. var FRONT = 1;
  83274. var BACK = 2;
  83275. var SPANNING = 3;
  83276. // Classify each point as well as the entire polygon into one of the above
  83277. // four classes.
  83278. var polygonType = 0;
  83279. var types = [];
  83280. var i;
  83281. var t;
  83282. for (i = 0; i < polygon.vertices.length; i++) {
  83283. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83284. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83285. polygonType |= type;
  83286. types.push(type);
  83287. }
  83288. // Put the polygon in the correct list, splitting it when necessary.
  83289. switch (polygonType) {
  83290. case COPLANAR:
  83291. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83292. break;
  83293. case FRONT:
  83294. front.push(polygon);
  83295. break;
  83296. case BACK:
  83297. back.push(polygon);
  83298. break;
  83299. case SPANNING:
  83300. var f = [], b = [];
  83301. for (i = 0; i < polygon.vertices.length; i++) {
  83302. var j = (i + 1) % polygon.vertices.length;
  83303. var ti = types[i], tj = types[j];
  83304. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83305. if (ti !== BACK)
  83306. f.push(vi);
  83307. if (ti !== FRONT)
  83308. b.push(ti !== BACK ? vi.clone() : vi);
  83309. if ((ti | tj) === SPANNING) {
  83310. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83311. var v = vi.interpolate(vj, t);
  83312. f.push(v);
  83313. b.push(v.clone());
  83314. }
  83315. }
  83316. var poly;
  83317. if (f.length >= 3) {
  83318. poly = new Polygon(f, polygon.shared);
  83319. if (poly.plane)
  83320. front.push(poly);
  83321. }
  83322. if (b.length >= 3) {
  83323. poly = new Polygon(b, polygon.shared);
  83324. if (poly.plane)
  83325. back.push(poly);
  83326. }
  83327. break;
  83328. }
  83329. };
  83330. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83331. // point is on the plane.
  83332. Plane.EPSILON = 1e-5;
  83333. return Plane;
  83334. }());
  83335. // # class Polygon
  83336. // Represents a convex polygon. The vertices used to initialize a polygon must
  83337. // be coplanar and form a convex loop.
  83338. //
  83339. // Each convex polygon has a `shared` property, which is shared between all
  83340. // polygons that are clones of each other or were split from the same polygon.
  83341. // This can be used to define per-polygon properties (such as surface color).
  83342. var Polygon = /** @class */ (function () {
  83343. function Polygon(vertices, shared) {
  83344. this.vertices = vertices;
  83345. this.shared = shared;
  83346. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83347. }
  83348. Polygon.prototype.clone = function () {
  83349. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83350. return new Polygon(vertices, this.shared);
  83351. };
  83352. Polygon.prototype.flip = function () {
  83353. this.vertices.reverse().map(function (v) { v.flip(); });
  83354. this.plane.flip();
  83355. };
  83356. return Polygon;
  83357. }());
  83358. // # class Node
  83359. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83360. // by picking a polygon to split along. That polygon (and all other coplanar
  83361. // polygons) are added directly to that node and the other polygons are added to
  83362. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83363. // no distinction between internal and leaf nodes.
  83364. var Node = /** @class */ (function () {
  83365. function Node(polygons) {
  83366. this.plane = null;
  83367. this.front = null;
  83368. this.back = null;
  83369. this.polygons = new Array();
  83370. if (polygons) {
  83371. this.build(polygons);
  83372. }
  83373. }
  83374. Node.prototype.clone = function () {
  83375. var node = new Node();
  83376. node.plane = this.plane && this.plane.clone();
  83377. node.front = this.front && this.front.clone();
  83378. node.back = this.back && this.back.clone();
  83379. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83380. return node;
  83381. };
  83382. // Convert solid space to empty space and empty space to solid space.
  83383. Node.prototype.invert = function () {
  83384. for (var i = 0; i < this.polygons.length; i++) {
  83385. this.polygons[i].flip();
  83386. }
  83387. if (this.plane) {
  83388. this.plane.flip();
  83389. }
  83390. if (this.front) {
  83391. this.front.invert();
  83392. }
  83393. if (this.back) {
  83394. this.back.invert();
  83395. }
  83396. var temp = this.front;
  83397. this.front = this.back;
  83398. this.back = temp;
  83399. };
  83400. // Recursively remove all polygons in `polygons` that are inside this BSP
  83401. // tree.
  83402. Node.prototype.clipPolygons = function (polygons) {
  83403. if (!this.plane)
  83404. return polygons.slice();
  83405. var front = new Array(), back = new Array();
  83406. for (var i = 0; i < polygons.length; i++) {
  83407. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83408. }
  83409. if (this.front) {
  83410. front = this.front.clipPolygons(front);
  83411. }
  83412. if (this.back) {
  83413. back = this.back.clipPolygons(back);
  83414. }
  83415. else {
  83416. back = [];
  83417. }
  83418. return front.concat(back);
  83419. };
  83420. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83421. // `bsp`.
  83422. Node.prototype.clipTo = function (bsp) {
  83423. this.polygons = bsp.clipPolygons(this.polygons);
  83424. if (this.front)
  83425. this.front.clipTo(bsp);
  83426. if (this.back)
  83427. this.back.clipTo(bsp);
  83428. };
  83429. // Return a list of all polygons in this BSP tree.
  83430. Node.prototype.allPolygons = function () {
  83431. var polygons = this.polygons.slice();
  83432. if (this.front)
  83433. polygons = polygons.concat(this.front.allPolygons());
  83434. if (this.back)
  83435. polygons = polygons.concat(this.back.allPolygons());
  83436. return polygons;
  83437. };
  83438. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83439. // new polygons are filtered down to the bottom of the tree and become new
  83440. // nodes there. Each set of polygons is partitioned using the first polygon
  83441. // (no heuristic is used to pick a good split).
  83442. Node.prototype.build = function (polygons) {
  83443. if (!polygons.length)
  83444. return;
  83445. if (!this.plane)
  83446. this.plane = polygons[0].plane.clone();
  83447. var front = new Array(), back = new Array();
  83448. for (var i = 0; i < polygons.length; i++) {
  83449. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83450. }
  83451. if (front.length) {
  83452. if (!this.front)
  83453. this.front = new Node();
  83454. this.front.build(front);
  83455. }
  83456. if (back.length) {
  83457. if (!this.back)
  83458. this.back = new Node();
  83459. this.back.build(back);
  83460. }
  83461. };
  83462. return Node;
  83463. }());
  83464. var CSG = /** @class */ (function () {
  83465. function CSG() {
  83466. this.polygons = new Array();
  83467. }
  83468. // Convert BABYLON.Mesh to BABYLON.CSG
  83469. CSG.FromMesh = function (mesh) {
  83470. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83471. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83472. if (mesh instanceof BABYLON.Mesh) {
  83473. mesh.computeWorldMatrix(true);
  83474. matrix = mesh.getWorldMatrix();
  83475. meshPosition = mesh.position.clone();
  83476. meshRotation = mesh.rotation.clone();
  83477. if (mesh.rotationQuaternion) {
  83478. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83479. }
  83480. meshScaling = mesh.scaling.clone();
  83481. }
  83482. else {
  83483. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83484. }
  83485. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83486. var subMeshes = mesh.subMeshes;
  83487. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83488. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83489. vertices = [];
  83490. for (var j = 0; j < 3; j++) {
  83491. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83492. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83493. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83494. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83495. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83496. vertex = new Vertex(position, normal, uv);
  83497. vertices.push(vertex);
  83498. }
  83499. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83500. // To handle the case of degenerated triangle
  83501. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83502. if (polygon.plane)
  83503. polygons.push(polygon);
  83504. }
  83505. }
  83506. var csg = CSG.FromPolygons(polygons);
  83507. csg.matrix = matrix;
  83508. csg.position = meshPosition;
  83509. csg.rotation = meshRotation;
  83510. csg.scaling = meshScaling;
  83511. csg.rotationQuaternion = meshRotationQuaternion;
  83512. currentCSGMeshId++;
  83513. return csg;
  83514. };
  83515. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83516. CSG.FromPolygons = function (polygons) {
  83517. var csg = new CSG();
  83518. csg.polygons = polygons;
  83519. return csg;
  83520. };
  83521. CSG.prototype.clone = function () {
  83522. var csg = new CSG();
  83523. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83524. csg.copyTransformAttributes(this);
  83525. return csg;
  83526. };
  83527. CSG.prototype.union = function (csg) {
  83528. var a = new Node(this.clone().polygons);
  83529. var b = new Node(csg.clone().polygons);
  83530. a.clipTo(b);
  83531. b.clipTo(a);
  83532. b.invert();
  83533. b.clipTo(a);
  83534. b.invert();
  83535. a.build(b.allPolygons());
  83536. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83537. };
  83538. CSG.prototype.unionInPlace = function (csg) {
  83539. var a = new Node(this.polygons);
  83540. var b = new Node(csg.polygons);
  83541. a.clipTo(b);
  83542. b.clipTo(a);
  83543. b.invert();
  83544. b.clipTo(a);
  83545. b.invert();
  83546. a.build(b.allPolygons());
  83547. this.polygons = a.allPolygons();
  83548. };
  83549. CSG.prototype.subtract = function (csg) {
  83550. var a = new Node(this.clone().polygons);
  83551. var b = new Node(csg.clone().polygons);
  83552. a.invert();
  83553. a.clipTo(b);
  83554. b.clipTo(a);
  83555. b.invert();
  83556. b.clipTo(a);
  83557. b.invert();
  83558. a.build(b.allPolygons());
  83559. a.invert();
  83560. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83561. };
  83562. CSG.prototype.subtractInPlace = function (csg) {
  83563. var a = new Node(this.polygons);
  83564. var b = new Node(csg.polygons);
  83565. a.invert();
  83566. a.clipTo(b);
  83567. b.clipTo(a);
  83568. b.invert();
  83569. b.clipTo(a);
  83570. b.invert();
  83571. a.build(b.allPolygons());
  83572. a.invert();
  83573. this.polygons = a.allPolygons();
  83574. };
  83575. CSG.prototype.intersect = function (csg) {
  83576. var a = new Node(this.clone().polygons);
  83577. var b = new Node(csg.clone().polygons);
  83578. a.invert();
  83579. b.clipTo(a);
  83580. b.invert();
  83581. a.clipTo(b);
  83582. b.clipTo(a);
  83583. a.build(b.allPolygons());
  83584. a.invert();
  83585. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83586. };
  83587. CSG.prototype.intersectInPlace = function (csg) {
  83588. var a = new Node(this.polygons);
  83589. var b = new Node(csg.polygons);
  83590. a.invert();
  83591. b.clipTo(a);
  83592. b.invert();
  83593. a.clipTo(b);
  83594. b.clipTo(a);
  83595. a.build(b.allPolygons());
  83596. a.invert();
  83597. this.polygons = a.allPolygons();
  83598. };
  83599. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83600. // not modified.
  83601. CSG.prototype.inverse = function () {
  83602. var csg = this.clone();
  83603. csg.inverseInPlace();
  83604. return csg;
  83605. };
  83606. CSG.prototype.inverseInPlace = function () {
  83607. this.polygons.map(function (p) { p.flip(); });
  83608. };
  83609. // This is used to keep meshes transformations so they can be restored
  83610. // when we build back a Babylon Mesh
  83611. // NB : All CSG operations are performed in world coordinates
  83612. CSG.prototype.copyTransformAttributes = function (csg) {
  83613. this.matrix = csg.matrix;
  83614. this.position = csg.position;
  83615. this.rotation = csg.rotation;
  83616. this.scaling = csg.scaling;
  83617. this.rotationQuaternion = csg.rotationQuaternion;
  83618. return this;
  83619. };
  83620. // Build Raw mesh from CSG
  83621. // Coordinates here are in world space
  83622. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83623. var matrix = this.matrix.clone();
  83624. matrix.invert();
  83625. 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;
  83626. if (keepSubMeshes) {
  83627. // Sort Polygons, since subMeshes are indices range
  83628. polygons.sort(function (a, b) {
  83629. if (a.shared.meshId === b.shared.meshId) {
  83630. return a.shared.subMeshId - b.shared.subMeshId;
  83631. }
  83632. else {
  83633. return a.shared.meshId - b.shared.meshId;
  83634. }
  83635. });
  83636. }
  83637. for (var i = 0, il = polygons.length; i < il; i++) {
  83638. polygon = polygons[i];
  83639. // Building SubMeshes
  83640. if (!subMesh_dict[polygon.shared.meshId]) {
  83641. subMesh_dict[polygon.shared.meshId] = {};
  83642. }
  83643. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83644. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83645. indexStart: +Infinity,
  83646. indexEnd: -Infinity,
  83647. materialIndex: polygon.shared.materialIndex
  83648. };
  83649. }
  83650. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83651. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83652. polygonIndices[0] = 0;
  83653. polygonIndices[1] = j - 1;
  83654. polygonIndices[2] = j;
  83655. for (var k = 0; k < 3; k++) {
  83656. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83657. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83658. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83659. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83660. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83661. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83662. // Check if 2 points can be merged
  83663. if (!(typeof vertex_idx !== 'undefined' &&
  83664. normals[vertex_idx * 3] === localNormal.x &&
  83665. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83666. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83667. uvs[vertex_idx * 2] === uv.x &&
  83668. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83669. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83670. uvs.push(uv.x, uv.y);
  83671. normals.push(normal.x, normal.y, normal.z);
  83672. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83673. }
  83674. indices.push(vertex_idx);
  83675. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83676. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83677. currentIndex++;
  83678. }
  83679. }
  83680. }
  83681. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83682. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83683. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83684. mesh.setIndices(indices, null);
  83685. if (keepSubMeshes) {
  83686. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83687. var materialIndexOffset = 0, materialMaxIndex;
  83688. mesh.subMeshes = new Array();
  83689. for (var m in subMesh_dict) {
  83690. materialMaxIndex = -1;
  83691. for (var sm in subMesh_dict[m]) {
  83692. subMesh_obj = subMesh_dict[m][sm];
  83693. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83694. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83695. }
  83696. materialIndexOffset += ++materialMaxIndex;
  83697. }
  83698. }
  83699. return mesh;
  83700. };
  83701. // Build Mesh from CSG taking material and transforms into account
  83702. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83703. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83704. mesh.material = material;
  83705. mesh.position.copyFrom(this.position);
  83706. mesh.rotation.copyFrom(this.rotation);
  83707. if (this.rotationQuaternion) {
  83708. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83709. }
  83710. mesh.scaling.copyFrom(this.scaling);
  83711. mesh.computeWorldMatrix(true);
  83712. return mesh;
  83713. };
  83714. return CSG;
  83715. }());
  83716. BABYLON.CSG = CSG;
  83717. })(BABYLON || (BABYLON = {}));
  83718. //# sourceMappingURL=babylon.csg.js.map
  83719. var BABYLON;
  83720. (function (BABYLON) {
  83721. var LensFlare = /** @class */ (function () {
  83722. function LensFlare(size, position, color, imgUrl, system) {
  83723. this.size = size;
  83724. this.position = position;
  83725. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83726. this.color = color || new BABYLON.Color3(1, 1, 1);
  83727. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83728. this._system = system;
  83729. system.lensFlares.push(this);
  83730. }
  83731. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83732. return new LensFlare(size, position, color, imgUrl, system);
  83733. };
  83734. LensFlare.prototype.dispose = function () {
  83735. if (this.texture) {
  83736. this.texture.dispose();
  83737. }
  83738. // Remove from scene
  83739. var index = this._system.lensFlares.indexOf(this);
  83740. this._system.lensFlares.splice(index, 1);
  83741. };
  83742. ;
  83743. return LensFlare;
  83744. }());
  83745. BABYLON.LensFlare = LensFlare;
  83746. })(BABYLON || (BABYLON = {}));
  83747. //# sourceMappingURL=babylon.lensFlare.js.map
  83748. var BABYLON;
  83749. (function (BABYLON) {
  83750. // Adds the parser to the scene parsers.
  83751. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  83752. // Lens flares
  83753. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  83754. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  83755. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  83756. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  83757. container.lensFlareSystems.push(lf);
  83758. }
  83759. }
  83760. });
  83761. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  83762. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  83763. if (this.lensFlareSystems[index].name === name) {
  83764. return this.lensFlareSystems[index];
  83765. }
  83766. }
  83767. return null;
  83768. };
  83769. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  83770. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  83771. if (this.lensFlareSystems[index].id === id) {
  83772. return this.lensFlareSystems[index];
  83773. }
  83774. }
  83775. return null;
  83776. };
  83777. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  83778. var index = this.lensFlareSystems.indexOf(toRemove);
  83779. if (index !== -1) {
  83780. this.lensFlareSystems.splice(index, 1);
  83781. }
  83782. return index;
  83783. };
  83784. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  83785. this.lensFlareSystems.push(newLensFlareSystem);
  83786. };
  83787. /**
  83788. * Defines the layer scene component responsible to manage any layers
  83789. * in a given scene.
  83790. */
  83791. var LensFlareSystemSceneComponent = /** @class */ (function () {
  83792. /**
  83793. * Creates a new instance of the component for the given scene
  83794. * @param scene Defines the scene to register the component in
  83795. */
  83796. function LensFlareSystemSceneComponent(scene) {
  83797. /**
  83798. * The component name helpfull to identify the component in the list of scene components.
  83799. */
  83800. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  83801. this.scene = scene;
  83802. this._lensFlareSystems = scene.lensFlareSystems = new Array();
  83803. }
  83804. /**
  83805. * Registers the component in a given scene
  83806. */
  83807. LensFlareSystemSceneComponent.prototype.register = function () {
  83808. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  83809. };
  83810. /**
  83811. * Rebuilds the elements related to this component in case of
  83812. * context lost for instance.
  83813. */
  83814. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  83815. // Nothing to do for lens flare
  83816. };
  83817. /**
  83818. * Adds all the element from the container to the scene
  83819. * @param container the container holding the elements
  83820. */
  83821. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  83822. var _this = this;
  83823. if (!container.lensFlareSystems) {
  83824. return;
  83825. }
  83826. container.lensFlareSystems.forEach(function (o) {
  83827. _this.scene.addLensFlareSystem(o);
  83828. });
  83829. };
  83830. /**
  83831. * Removes all the elements in the container from the scene
  83832. * @param container contains the elements to remove
  83833. */
  83834. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  83835. var _this = this;
  83836. if (!container.lensFlareSystems) {
  83837. return;
  83838. }
  83839. container.lensFlareSystems.forEach(function (o) {
  83840. _this.scene.removeLensFlareSystem(o);
  83841. });
  83842. };
  83843. /**
  83844. * Serializes the component data to the specified json object
  83845. * @param serializationObject The object to serialize to
  83846. */
  83847. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  83848. // Lens flares
  83849. serializationObject.lensFlareSystems = [];
  83850. for (var _i = 0, _a = this._lensFlareSystems; _i < _a.length; _i++) {
  83851. var lensFlareSystem = _a[_i];
  83852. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  83853. }
  83854. };
  83855. /**
  83856. * Disposes the component and the associated ressources.
  83857. */
  83858. LensFlareSystemSceneComponent.prototype.dispose = function () {
  83859. while (this._lensFlareSystems.length) {
  83860. this._lensFlareSystems[0].dispose();
  83861. }
  83862. };
  83863. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  83864. // Lens flares
  83865. if (this.scene.lensFlaresEnabled) {
  83866. BABYLON.Tools.StartPerformanceCounter("Lens flares", this._lensFlareSystems.length > 0);
  83867. for (var _i = 0, _a = this._lensFlareSystems; _i < _a.length; _i++) {
  83868. var lensFlareSystem = _a[_i];
  83869. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  83870. lensFlareSystem.render();
  83871. }
  83872. }
  83873. BABYLON.Tools.EndPerformanceCounter("Lens flares", this._lensFlareSystems.length > 0);
  83874. }
  83875. };
  83876. return LensFlareSystemSceneComponent;
  83877. }());
  83878. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  83879. })(BABYLON || (BABYLON = {}));
  83880. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  83881. var BABYLON;
  83882. (function (BABYLON) {
  83883. var LensFlareSystem = /** @class */ (function () {
  83884. function LensFlareSystem(name, emitter, scene) {
  83885. this.name = name;
  83886. this.lensFlares = new Array();
  83887. this.borderLimit = 300;
  83888. this.viewportBorder = 0;
  83889. this.layerMask = 0x0FFFFFFF;
  83890. this._vertexBuffers = {};
  83891. this._isEnabled = true;
  83892. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83893. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  83894. if (!component) {
  83895. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  83896. scene._addComponent(component);
  83897. }
  83898. this._emitter = emitter;
  83899. this.id = name;
  83900. scene.lensFlareSystems.push(this);
  83901. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  83902. var engine = scene.getEngine();
  83903. // VBO
  83904. var vertices = [];
  83905. vertices.push(1, 1);
  83906. vertices.push(-1, 1);
  83907. vertices.push(-1, -1);
  83908. vertices.push(1, -1);
  83909. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83910. // Indices
  83911. var indices = [];
  83912. indices.push(0);
  83913. indices.push(1);
  83914. indices.push(2);
  83915. indices.push(0);
  83916. indices.push(2);
  83917. indices.push(3);
  83918. this._indexBuffer = engine.createIndexBuffer(indices);
  83919. // Effects
  83920. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  83921. }
  83922. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  83923. get: function () {
  83924. return this._isEnabled;
  83925. },
  83926. set: function (value) {
  83927. this._isEnabled = value;
  83928. },
  83929. enumerable: true,
  83930. configurable: true
  83931. });
  83932. LensFlareSystem.prototype.getScene = function () {
  83933. return this._scene;
  83934. };
  83935. LensFlareSystem.prototype.getEmitter = function () {
  83936. return this._emitter;
  83937. };
  83938. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  83939. this._emitter = newEmitter;
  83940. };
  83941. LensFlareSystem.prototype.getEmitterPosition = function () {
  83942. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  83943. };
  83944. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  83945. var position = this.getEmitterPosition();
  83946. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  83947. this._positionX = position.x;
  83948. this._positionY = position.y;
  83949. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  83950. if (this.viewportBorder > 0) {
  83951. globalViewport.x -= this.viewportBorder;
  83952. globalViewport.y -= this.viewportBorder;
  83953. globalViewport.width += this.viewportBorder * 2;
  83954. globalViewport.height += this.viewportBorder * 2;
  83955. position.x += this.viewportBorder;
  83956. position.y += this.viewportBorder;
  83957. this._positionX += this.viewportBorder;
  83958. this._positionY += this.viewportBorder;
  83959. }
  83960. if (position.z > 0) {
  83961. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  83962. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  83963. return true;
  83964. }
  83965. return true;
  83966. }
  83967. return false;
  83968. };
  83969. LensFlareSystem.prototype._isVisible = function () {
  83970. if (!this._isEnabled || !this._scene.activeCamera) {
  83971. return false;
  83972. }
  83973. var emitterPosition = this.getEmitterPosition();
  83974. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  83975. var distance = direction.length();
  83976. direction.normalize();
  83977. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  83978. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  83979. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  83980. };
  83981. LensFlareSystem.prototype.render = function () {
  83982. if (!this._effect.isReady() || !this._scene.activeCamera)
  83983. return false;
  83984. var engine = this._scene.getEngine();
  83985. var viewport = this._scene.activeCamera.viewport;
  83986. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  83987. // Position
  83988. if (!this.computeEffectivePosition(globalViewport)) {
  83989. return false;
  83990. }
  83991. // Visibility
  83992. if (!this._isVisible()) {
  83993. return false;
  83994. }
  83995. // Intensity
  83996. var awayX;
  83997. var awayY;
  83998. if (this._positionX < this.borderLimit + globalViewport.x) {
  83999. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84000. }
  84001. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84002. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84003. }
  84004. else {
  84005. awayX = 0;
  84006. }
  84007. if (this._positionY < this.borderLimit + globalViewport.y) {
  84008. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84009. }
  84010. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84011. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84012. }
  84013. else {
  84014. awayY = 0;
  84015. }
  84016. var away = (awayX > awayY) ? awayX : awayY;
  84017. away -= this.viewportBorder;
  84018. if (away > this.borderLimit) {
  84019. away = this.borderLimit;
  84020. }
  84021. var intensity = 1.0 - (away / this.borderLimit);
  84022. if (intensity < 0) {
  84023. return false;
  84024. }
  84025. if (intensity > 1.0) {
  84026. intensity = 1.0;
  84027. }
  84028. if (this.viewportBorder > 0) {
  84029. globalViewport.x += this.viewportBorder;
  84030. globalViewport.y += this.viewportBorder;
  84031. globalViewport.width -= this.viewportBorder * 2;
  84032. globalViewport.height -= this.viewportBorder * 2;
  84033. this._positionX -= this.viewportBorder;
  84034. this._positionY -= this.viewportBorder;
  84035. }
  84036. // Position
  84037. var centerX = globalViewport.x + globalViewport.width / 2;
  84038. var centerY = globalViewport.y + globalViewport.height / 2;
  84039. var distX = centerX - this._positionX;
  84040. var distY = centerY - this._positionY;
  84041. // Effects
  84042. engine.enableEffect(this._effect);
  84043. engine.setState(false);
  84044. engine.setDepthBuffer(false);
  84045. // VBOs
  84046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84047. // Flares
  84048. for (var index = 0; index < this.lensFlares.length; index++) {
  84049. var flare = this.lensFlares[index];
  84050. engine.setAlphaMode(flare.alphaMode);
  84051. var x = centerX - (distX * flare.position);
  84052. var y = centerY - (distY * flare.position);
  84053. var cw = flare.size;
  84054. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84055. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84056. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84057. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84058. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84059. // Texture
  84060. this._effect.setTexture("textureSampler", flare.texture);
  84061. // Color
  84062. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84063. // Draw order
  84064. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84065. }
  84066. engine.setDepthBuffer(true);
  84067. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84068. return true;
  84069. };
  84070. LensFlareSystem.prototype.dispose = function () {
  84071. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84072. if (vertexBuffer) {
  84073. vertexBuffer.dispose();
  84074. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84075. }
  84076. if (this._indexBuffer) {
  84077. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84078. this._indexBuffer = null;
  84079. }
  84080. while (this.lensFlares.length) {
  84081. this.lensFlares[0].dispose();
  84082. }
  84083. // Remove from scene
  84084. var index = this._scene.lensFlareSystems.indexOf(this);
  84085. this._scene.lensFlareSystems.splice(index, 1);
  84086. };
  84087. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84088. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84089. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84090. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84091. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84092. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84093. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84094. var parsedFlare = parsedLensFlareSystem.flares[index];
  84095. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84096. }
  84097. return lensFlareSystem;
  84098. };
  84099. LensFlareSystem.prototype.serialize = function () {
  84100. var serializationObject = {};
  84101. serializationObject.id = this.id;
  84102. serializationObject.name = this.name;
  84103. serializationObject.emitterId = this.getEmitter().id;
  84104. serializationObject.borderLimit = this.borderLimit;
  84105. serializationObject.flares = [];
  84106. for (var index = 0; index < this.lensFlares.length; index++) {
  84107. var flare = this.lensFlares[index];
  84108. serializationObject.flares.push({
  84109. size: flare.size,
  84110. position: flare.position,
  84111. color: flare.color.asArray(),
  84112. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84113. });
  84114. }
  84115. return serializationObject;
  84116. };
  84117. return LensFlareSystem;
  84118. }());
  84119. BABYLON.LensFlareSystem = LensFlareSystem;
  84120. })(BABYLON || (BABYLON = {}));
  84121. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84122. var BABYLON;
  84123. (function (BABYLON) {
  84124. /**
  84125. * This is a holder class for the physics joint created by the physics plugin.
  84126. * It holds a set of functions to control the underlying joint.
  84127. */
  84128. var PhysicsJoint = /** @class */ (function () {
  84129. function PhysicsJoint(type, jointData) {
  84130. this.type = type;
  84131. this.jointData = jointData;
  84132. jointData.nativeParams = jointData.nativeParams || {};
  84133. }
  84134. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84135. get: function () {
  84136. return this._physicsJoint;
  84137. },
  84138. set: function (newJoint) {
  84139. if (this._physicsJoint) {
  84140. //remove from the wolrd
  84141. }
  84142. this._physicsJoint = newJoint;
  84143. },
  84144. enumerable: true,
  84145. configurable: true
  84146. });
  84147. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84148. set: function (physicsPlugin) {
  84149. this._physicsPlugin = physicsPlugin;
  84150. },
  84151. enumerable: true,
  84152. configurable: true
  84153. });
  84154. /**
  84155. * Execute a function that is physics-plugin specific.
  84156. * @param {Function} func the function that will be executed.
  84157. * It accepts two parameters: the physics world and the physics joint.
  84158. */
  84159. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84160. func(this._physicsPlugin.world, this._physicsJoint);
  84161. };
  84162. //TODO check if the native joints are the same
  84163. //Joint Types
  84164. PhysicsJoint.DistanceJoint = 0;
  84165. PhysicsJoint.HingeJoint = 1;
  84166. PhysicsJoint.BallAndSocketJoint = 2;
  84167. PhysicsJoint.WheelJoint = 3;
  84168. PhysicsJoint.SliderJoint = 4;
  84169. //OIMO
  84170. PhysicsJoint.PrismaticJoint = 5;
  84171. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84172. PhysicsJoint.UniversalJoint = 6;
  84173. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84174. //Cannon
  84175. //Similar to a Ball-Joint. Different in params
  84176. PhysicsJoint.PointToPointJoint = 8;
  84177. //Cannon only at the moment
  84178. PhysicsJoint.SpringJoint = 9;
  84179. PhysicsJoint.LockJoint = 10;
  84180. return PhysicsJoint;
  84181. }());
  84182. BABYLON.PhysicsJoint = PhysicsJoint;
  84183. /**
  84184. * A class representing a physics distance joint.
  84185. */
  84186. var DistanceJoint = /** @class */ (function (_super) {
  84187. __extends(DistanceJoint, _super);
  84188. function DistanceJoint(jointData) {
  84189. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84190. }
  84191. /**
  84192. * Update the predefined distance.
  84193. */
  84194. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84195. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84196. };
  84197. return DistanceJoint;
  84198. }(PhysicsJoint));
  84199. BABYLON.DistanceJoint = DistanceJoint;
  84200. var MotorEnabledJoint = /** @class */ (function (_super) {
  84201. __extends(MotorEnabledJoint, _super);
  84202. function MotorEnabledJoint(type, jointData) {
  84203. return _super.call(this, type, jointData) || this;
  84204. }
  84205. /**
  84206. * Set the motor values.
  84207. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84208. * @param {number} force the force to apply
  84209. * @param {number} maxForce max force for this motor.
  84210. */
  84211. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84212. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84213. };
  84214. /**
  84215. * Set the motor's limits.
  84216. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84217. */
  84218. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84219. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84220. };
  84221. return MotorEnabledJoint;
  84222. }(PhysicsJoint));
  84223. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84224. /**
  84225. * This class represents a single hinge physics joint
  84226. */
  84227. var HingeJoint = /** @class */ (function (_super) {
  84228. __extends(HingeJoint, _super);
  84229. function HingeJoint(jointData) {
  84230. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84231. }
  84232. /**
  84233. * Set the motor values.
  84234. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84235. * @param {number} force the force to apply
  84236. * @param {number} maxForce max force for this motor.
  84237. */
  84238. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84239. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84240. };
  84241. /**
  84242. * Set the motor's limits.
  84243. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84244. */
  84245. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84246. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84247. };
  84248. return HingeJoint;
  84249. }(MotorEnabledJoint));
  84250. BABYLON.HingeJoint = HingeJoint;
  84251. /**
  84252. * This class represents a dual hinge physics joint (same as wheel joint)
  84253. */
  84254. var Hinge2Joint = /** @class */ (function (_super) {
  84255. __extends(Hinge2Joint, _super);
  84256. function Hinge2Joint(jointData) {
  84257. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84258. }
  84259. /**
  84260. * Set the motor values.
  84261. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84262. * @param {number} force the force to apply
  84263. * @param {number} maxForce max force for this motor.
  84264. * @param {motorIndex} the motor's index, 0 or 1.
  84265. */
  84266. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84267. if (motorIndex === void 0) { motorIndex = 0; }
  84268. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84269. };
  84270. /**
  84271. * Set the motor limits.
  84272. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84273. * @param {number} upperLimit the upper limit
  84274. * @param {number} lowerLimit lower limit
  84275. * @param {motorIndex} the motor's index, 0 or 1.
  84276. */
  84277. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84278. if (motorIndex === void 0) { motorIndex = 0; }
  84279. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84280. };
  84281. return Hinge2Joint;
  84282. }(MotorEnabledJoint));
  84283. BABYLON.Hinge2Joint = Hinge2Joint;
  84284. })(BABYLON || (BABYLON = {}));
  84285. //# sourceMappingURL=babylon.physicsJoint.js.map
  84286. var BABYLON;
  84287. (function (BABYLON) {
  84288. var PhysicsImpostor = /** @class */ (function () {
  84289. function PhysicsImpostor(object, type, _options, _scene) {
  84290. if (_options === void 0) { _options = { mass: 0 }; }
  84291. var _this = this;
  84292. this.object = object;
  84293. this.type = type;
  84294. this._options = _options;
  84295. this._scene = _scene;
  84296. this._bodyUpdateRequired = false;
  84297. this._onBeforePhysicsStepCallbacks = new Array();
  84298. this._onAfterPhysicsStepCallbacks = new Array();
  84299. this._onPhysicsCollideCallbacks = [];
  84300. this._deltaPosition = BABYLON.Vector3.Zero();
  84301. this._isDisposed = false;
  84302. //temp variables for parent rotation calculations
  84303. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84304. this._tmpQuat = new BABYLON.Quaternion();
  84305. this._tmpQuat2 = new BABYLON.Quaternion();
  84306. /**
  84307. * this function is executed by the physics engine.
  84308. */
  84309. this.beforeStep = function () {
  84310. if (!_this._physicsEngine) {
  84311. return;
  84312. }
  84313. _this.object.translate(_this._deltaPosition, -1);
  84314. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84315. _this.object.computeWorldMatrix(false);
  84316. if (_this.object.parent && _this.object.rotationQuaternion) {
  84317. _this.getParentsRotation();
  84318. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84319. }
  84320. else {
  84321. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84322. }
  84323. if (!_this._options.disableBidirectionalTransformation) {
  84324. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84325. }
  84326. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84327. func(_this);
  84328. });
  84329. };
  84330. /**
  84331. * this function is executed by the physics engine.
  84332. */
  84333. this.afterStep = function () {
  84334. if (!_this._physicsEngine) {
  84335. return;
  84336. }
  84337. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84338. func(_this);
  84339. });
  84340. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84341. // object has now its world rotation. needs to be converted to local.
  84342. if (_this.object.parent && _this.object.rotationQuaternion) {
  84343. _this.getParentsRotation();
  84344. _this._tmpQuat.conjugateInPlace();
  84345. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84346. }
  84347. // take the position set and make it the absolute position of this object.
  84348. _this.object.setAbsolutePosition(_this.object.position);
  84349. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84350. _this.object.translate(_this._deltaPosition, 1);
  84351. };
  84352. /**
  84353. * Legacy collision detection event support
  84354. */
  84355. this.onCollideEvent = null;
  84356. //event and body object due to cannon's event-based architecture.
  84357. this.onCollide = function (e) {
  84358. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84359. return;
  84360. }
  84361. if (!_this._physicsEngine) {
  84362. return;
  84363. }
  84364. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84365. if (otherImpostor) {
  84366. // Legacy collision detection event support
  84367. if (_this.onCollideEvent) {
  84368. _this.onCollideEvent(_this, otherImpostor);
  84369. }
  84370. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84371. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84372. }).forEach(function (obj) {
  84373. obj.callback(_this, otherImpostor);
  84374. });
  84375. }
  84376. };
  84377. //sanity check!
  84378. if (!this.object) {
  84379. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84380. return;
  84381. }
  84382. //legacy support for old syntax.
  84383. if (!this._scene && object.getScene) {
  84384. this._scene = object.getScene();
  84385. }
  84386. if (!this._scene) {
  84387. return;
  84388. }
  84389. this._physicsEngine = this._scene.getPhysicsEngine();
  84390. if (!this._physicsEngine) {
  84391. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84392. }
  84393. else {
  84394. //set the object's quaternion, if not set
  84395. if (!this.object.rotationQuaternion) {
  84396. if (this.object.rotation) {
  84397. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84398. }
  84399. else {
  84400. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84401. }
  84402. }
  84403. //default options params
  84404. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84405. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84406. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84407. this._joints = [];
  84408. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84409. if (!this.object.parent || this._options.ignoreParent) {
  84410. this._init();
  84411. }
  84412. else if (this.object.parent.physicsImpostor) {
  84413. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84414. }
  84415. }
  84416. }
  84417. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84418. get: function () {
  84419. return this._isDisposed;
  84420. },
  84421. enumerable: true,
  84422. configurable: true
  84423. });
  84424. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84425. get: function () {
  84426. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84427. },
  84428. set: function (value) {
  84429. this.setMass(value);
  84430. },
  84431. enumerable: true,
  84432. configurable: true
  84433. });
  84434. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84435. get: function () {
  84436. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84437. },
  84438. set: function (value) {
  84439. if (!this._physicsEngine) {
  84440. return;
  84441. }
  84442. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84443. },
  84444. enumerable: true,
  84445. configurable: true
  84446. });
  84447. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84448. get: function () {
  84449. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84450. },
  84451. set: function (value) {
  84452. if (!this._physicsEngine) {
  84453. return;
  84454. }
  84455. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84456. },
  84457. enumerable: true,
  84458. configurable: true
  84459. });
  84460. /**
  84461. * This function will completly initialize this impostor.
  84462. * It will create a new body - but only if this mesh has no parent.
  84463. * If it has, this impostor will not be used other than to define the impostor
  84464. * of the child mesh.
  84465. */
  84466. PhysicsImpostor.prototype._init = function () {
  84467. if (!this._physicsEngine) {
  84468. return;
  84469. }
  84470. this._physicsEngine.removeImpostor(this);
  84471. this.physicsBody = null;
  84472. this._parent = this._parent || this._getPhysicsParent();
  84473. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84474. this._physicsEngine.addImpostor(this);
  84475. }
  84476. };
  84477. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84478. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84479. var parentMesh = this.object.parent;
  84480. return parentMesh.physicsImpostor;
  84481. }
  84482. return null;
  84483. };
  84484. /**
  84485. * Should a new body be generated.
  84486. */
  84487. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84488. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84489. };
  84490. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84491. this.forceUpdate();
  84492. };
  84493. /**
  84494. * Force a regeneration of this or the parent's impostor's body.
  84495. * Use under cautious - This will remove all joints already implemented.
  84496. */
  84497. PhysicsImpostor.prototype.forceUpdate = function () {
  84498. this._init();
  84499. if (this.parent && !this._options.ignoreParent) {
  84500. this.parent.forceUpdate();
  84501. }
  84502. };
  84503. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84504. /*public get mesh(): AbstractMesh {
  84505. return this._mesh;
  84506. }*/
  84507. /**
  84508. * Gets the body that holds this impostor. Either its own, or its parent.
  84509. */
  84510. get: function () {
  84511. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84512. },
  84513. /**
  84514. * Set the physics body. Used mainly by the physics engine/plugin
  84515. */
  84516. set: function (physicsBody) {
  84517. if (this._physicsBody && this._physicsEngine) {
  84518. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84519. }
  84520. this._physicsBody = physicsBody;
  84521. this.resetUpdateFlags();
  84522. },
  84523. enumerable: true,
  84524. configurable: true
  84525. });
  84526. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84527. get: function () {
  84528. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84529. },
  84530. set: function (value) {
  84531. this._parent = value;
  84532. },
  84533. enumerable: true,
  84534. configurable: true
  84535. });
  84536. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84537. this._bodyUpdateRequired = false;
  84538. };
  84539. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84540. if (this.object.getBoundingInfo) {
  84541. var q = this.object.rotationQuaternion;
  84542. //reset rotation
  84543. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84544. //calculate the world matrix with no rotation
  84545. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84546. var boundingInfo = this.object.getBoundingInfo();
  84547. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84548. //bring back the rotation
  84549. this.object.rotationQuaternion = q;
  84550. //calculate the world matrix with the new rotation
  84551. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84552. return size;
  84553. }
  84554. else {
  84555. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84556. }
  84557. };
  84558. PhysicsImpostor.prototype.getObjectCenter = function () {
  84559. if (this.object.getBoundingInfo) {
  84560. var boundingInfo = this.object.getBoundingInfo();
  84561. return boundingInfo.boundingBox.centerWorld;
  84562. }
  84563. else {
  84564. return this.object.position;
  84565. }
  84566. };
  84567. /**
  84568. * Get a specific parametes from the options parameter.
  84569. */
  84570. PhysicsImpostor.prototype.getParam = function (paramName) {
  84571. return this._options[paramName];
  84572. };
  84573. /**
  84574. * Sets a specific parameter in the options given to the physics plugin
  84575. */
  84576. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84577. this._options[paramName] = value;
  84578. this._bodyUpdateRequired = true;
  84579. };
  84580. /**
  84581. * Specifically change the body's mass option. Won't recreate the physics body object
  84582. */
  84583. PhysicsImpostor.prototype.setMass = function (mass) {
  84584. if (this.getParam("mass") !== mass) {
  84585. this.setParam("mass", mass);
  84586. }
  84587. if (this._physicsEngine) {
  84588. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84589. }
  84590. };
  84591. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84592. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84593. };
  84594. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84595. if (this._physicsEngine) {
  84596. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84597. }
  84598. };
  84599. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84600. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84601. };
  84602. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84603. if (this._physicsEngine) {
  84604. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84605. }
  84606. };
  84607. /**
  84608. * Execute a function with the physics plugin native code.
  84609. * Provide a function the will have two variables - the world object and the physics body object.
  84610. */
  84611. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84612. if (this._physicsEngine) {
  84613. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84614. }
  84615. };
  84616. /**
  84617. * Register a function that will be executed before the physics world is stepping forward.
  84618. */
  84619. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84620. this._onBeforePhysicsStepCallbacks.push(func);
  84621. };
  84622. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84623. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84624. if (index > -1) {
  84625. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84626. }
  84627. else {
  84628. BABYLON.Tools.Warn("Function to remove was not found");
  84629. }
  84630. };
  84631. /**
  84632. * Register a function that will be executed after the physics step
  84633. */
  84634. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84635. this._onAfterPhysicsStepCallbacks.push(func);
  84636. };
  84637. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84638. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84639. if (index > -1) {
  84640. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84641. }
  84642. else {
  84643. BABYLON.Tools.Warn("Function to remove was not found");
  84644. }
  84645. };
  84646. /**
  84647. * register a function that will be executed when this impostor collides against a different body.
  84648. */
  84649. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84650. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84651. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84652. };
  84653. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84654. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84655. var index = -1;
  84656. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84657. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84658. // chcek the arrays match
  84659. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84660. return collidedAgainstList.indexOf(impostor) > -1;
  84661. });
  84662. if (sameList) {
  84663. index = idx;
  84664. }
  84665. return sameList;
  84666. }
  84667. return false;
  84668. });
  84669. if (found) {
  84670. this._onPhysicsCollideCallbacks.splice(index, 1);
  84671. }
  84672. else {
  84673. BABYLON.Tools.Warn("Function to remove was not found");
  84674. }
  84675. };
  84676. PhysicsImpostor.prototype.getParentsRotation = function () {
  84677. var parent = this.object.parent;
  84678. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84679. while (parent) {
  84680. if (parent.rotationQuaternion) {
  84681. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84682. }
  84683. else {
  84684. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84685. }
  84686. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84687. parent = parent.parent;
  84688. }
  84689. return this._tmpQuat;
  84690. };
  84691. /**
  84692. * Apply a force
  84693. */
  84694. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84695. if (this._physicsEngine) {
  84696. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84697. }
  84698. return this;
  84699. };
  84700. /**
  84701. * Apply an impulse
  84702. */
  84703. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84704. if (this._physicsEngine) {
  84705. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84706. }
  84707. return this;
  84708. };
  84709. /**
  84710. * A help function to create a joint.
  84711. */
  84712. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84713. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84714. this.addJoint(otherImpostor, joint);
  84715. return this;
  84716. };
  84717. /**
  84718. * Add a joint to this impostor with a different impostor.
  84719. */
  84720. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84721. this._joints.push({
  84722. otherImpostor: otherImpostor,
  84723. joint: joint
  84724. });
  84725. if (this._physicsEngine) {
  84726. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84727. }
  84728. return this;
  84729. };
  84730. /**
  84731. * Will keep this body still, in a sleep mode.
  84732. */
  84733. PhysicsImpostor.prototype.sleep = function () {
  84734. if (this._physicsEngine) {
  84735. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84736. }
  84737. return this;
  84738. };
  84739. /**
  84740. * Wake the body up.
  84741. */
  84742. PhysicsImpostor.prototype.wakeUp = function () {
  84743. if (this._physicsEngine) {
  84744. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84745. }
  84746. return this;
  84747. };
  84748. PhysicsImpostor.prototype.clone = function (newObject) {
  84749. if (!newObject)
  84750. return null;
  84751. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84752. };
  84753. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84754. var _this = this;
  84755. //no dispose if no physics engine is available.
  84756. if (!this._physicsEngine) {
  84757. return;
  84758. }
  84759. this._joints.forEach(function (j) {
  84760. if (_this._physicsEngine) {
  84761. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84762. }
  84763. });
  84764. //dispose the physics body
  84765. this._physicsEngine.removeImpostor(this);
  84766. if (this.parent) {
  84767. this.parent.forceUpdate();
  84768. }
  84769. else {
  84770. /*this._object.getChildMeshes().forEach(function(mesh) {
  84771. if (mesh.physicsImpostor) {
  84772. if (disposeChildren) {
  84773. mesh.physicsImpostor.dispose();
  84774. mesh.physicsImpostor = null;
  84775. }
  84776. }
  84777. })*/
  84778. }
  84779. this._isDisposed = true;
  84780. };
  84781. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84782. this._deltaPosition.copyFrom(position);
  84783. };
  84784. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84785. if (!this._deltaRotation) {
  84786. this._deltaRotation = new BABYLON.Quaternion();
  84787. }
  84788. this._deltaRotation.copyFrom(rotation);
  84789. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84790. };
  84791. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84792. if (this._physicsEngine) {
  84793. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84794. }
  84795. return this;
  84796. };
  84797. PhysicsImpostor.prototype.getRadius = function () {
  84798. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84799. };
  84800. /**
  84801. * Sync a bone with this impostor
  84802. * @param bone The bone to sync to the impostor.
  84803. * @param boneMesh The mesh that the bone is influencing.
  84804. * @param jointPivot The pivot of the joint / bone in local space.
  84805. * @param distToJoint Optional distance from the impostor to the joint.
  84806. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84807. */
  84808. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84809. var tempVec = PhysicsImpostor._tmpVecs[0];
  84810. var mesh = this.object;
  84811. if (mesh.rotationQuaternion) {
  84812. if (adjustRotation) {
  84813. var tempQuat = PhysicsImpostor._tmpQuat;
  84814. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84815. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84816. }
  84817. else {
  84818. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84819. }
  84820. }
  84821. tempVec.x = 0;
  84822. tempVec.y = 0;
  84823. tempVec.z = 0;
  84824. if (jointPivot) {
  84825. tempVec.x = jointPivot.x;
  84826. tempVec.y = jointPivot.y;
  84827. tempVec.z = jointPivot.z;
  84828. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84829. if (distToJoint === undefined || distToJoint === null) {
  84830. distToJoint = jointPivot.length();
  84831. }
  84832. tempVec.x *= distToJoint;
  84833. tempVec.y *= distToJoint;
  84834. tempVec.z *= distToJoint;
  84835. }
  84836. if (bone.getParent()) {
  84837. tempVec.addInPlace(mesh.getAbsolutePosition());
  84838. bone.setAbsolutePosition(tempVec, boneMesh);
  84839. }
  84840. else {
  84841. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84842. boneMesh.position.x -= tempVec.x;
  84843. boneMesh.position.y -= tempVec.y;
  84844. boneMesh.position.z -= tempVec.z;
  84845. }
  84846. };
  84847. /**
  84848. * Sync impostor to a bone
  84849. * @param bone The bone that the impostor will be synced to.
  84850. * @param boneMesh The mesh that the bone is influencing.
  84851. * @param jointPivot The pivot of the joint / bone in local space.
  84852. * @param distToJoint Optional distance from the impostor to the joint.
  84853. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84854. * @param boneAxis Optional vector3 axis the bone is aligned with
  84855. */
  84856. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84857. var mesh = this.object;
  84858. if (mesh.rotationQuaternion) {
  84859. if (adjustRotation) {
  84860. var tempQuat = PhysicsImpostor._tmpQuat;
  84861. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  84862. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  84863. }
  84864. else {
  84865. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  84866. }
  84867. }
  84868. var pos = PhysicsImpostor._tmpVecs[0];
  84869. var boneDir = PhysicsImpostor._tmpVecs[1];
  84870. if (!boneAxis) {
  84871. boneAxis = PhysicsImpostor._tmpVecs[2];
  84872. boneAxis.x = 0;
  84873. boneAxis.y = 1;
  84874. boneAxis.z = 0;
  84875. }
  84876. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  84877. bone.getAbsolutePositionToRef(boneMesh, pos);
  84878. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  84879. distToJoint = jointPivot.length();
  84880. }
  84881. if (distToJoint !== undefined && distToJoint !== null) {
  84882. pos.x += boneDir.x * distToJoint;
  84883. pos.y += boneDir.y * distToJoint;
  84884. pos.z += boneDir.z * distToJoint;
  84885. }
  84886. mesh.setAbsolutePosition(pos);
  84887. };
  84888. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  84889. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  84890. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84891. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  84892. //Impostor types
  84893. PhysicsImpostor.NoImpostor = 0;
  84894. PhysicsImpostor.SphereImpostor = 1;
  84895. PhysicsImpostor.BoxImpostor = 2;
  84896. PhysicsImpostor.PlaneImpostor = 3;
  84897. PhysicsImpostor.MeshImpostor = 4;
  84898. PhysicsImpostor.CylinderImpostor = 7;
  84899. PhysicsImpostor.ParticleImpostor = 8;
  84900. PhysicsImpostor.HeightmapImpostor = 9;
  84901. return PhysicsImpostor;
  84902. }());
  84903. BABYLON.PhysicsImpostor = PhysicsImpostor;
  84904. })(BABYLON || (BABYLON = {}));
  84905. //# sourceMappingURL=babylon.physicsImpostor.js.map
  84906. var BABYLON;
  84907. (function (BABYLON) {
  84908. var PhysicsEngine = /** @class */ (function () {
  84909. function PhysicsEngine(gravity, _physicsPlugin) {
  84910. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  84911. this._physicsPlugin = _physicsPlugin;
  84912. //new methods and parameters
  84913. this._impostors = [];
  84914. this._joints = [];
  84915. if (!this._physicsPlugin.isSupported()) {
  84916. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  84917. + "Please make sure it is included.");
  84918. }
  84919. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  84920. this.setGravity(gravity);
  84921. this.setTimeStep();
  84922. }
  84923. PhysicsEngine.prototype.setGravity = function (gravity) {
  84924. this.gravity = gravity;
  84925. this._physicsPlugin.setGravity(this.gravity);
  84926. };
  84927. /**
  84928. * Set the time step of the physics engine.
  84929. * default is 1/60.
  84930. * To slow it down, enter 1/600 for example.
  84931. * To speed it up, 1/30
  84932. * @param {number} newTimeStep the new timestep to apply to this world.
  84933. */
  84934. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  84935. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  84936. this._physicsPlugin.setTimeStep(newTimeStep);
  84937. };
  84938. /**
  84939. * Get the time step of the physics engine.
  84940. */
  84941. PhysicsEngine.prototype.getTimeStep = function () {
  84942. return this._physicsPlugin.getTimeStep();
  84943. };
  84944. PhysicsEngine.prototype.dispose = function () {
  84945. this._impostors.forEach(function (impostor) {
  84946. impostor.dispose();
  84947. });
  84948. this._physicsPlugin.dispose();
  84949. };
  84950. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  84951. return this._physicsPlugin.name;
  84952. };
  84953. /**
  84954. * Adding a new impostor for the impostor tracking.
  84955. * This will be done by the impostor itself.
  84956. * @param {PhysicsImpostor} impostor the impostor to add
  84957. */
  84958. PhysicsEngine.prototype.addImpostor = function (impostor) {
  84959. impostor.uniqueId = this._impostors.push(impostor);
  84960. //if no parent, generate the body
  84961. if (!impostor.parent) {
  84962. this._physicsPlugin.generatePhysicsBody(impostor);
  84963. }
  84964. };
  84965. /**
  84966. * Remove an impostor from the engine.
  84967. * This impostor and its mesh will not longer be updated by the physics engine.
  84968. * @param {PhysicsImpostor} impostor the impostor to remove
  84969. */
  84970. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  84971. var index = this._impostors.indexOf(impostor);
  84972. if (index > -1) {
  84973. var removed = this._impostors.splice(index, 1);
  84974. //Is it needed?
  84975. if (removed.length) {
  84976. //this will also remove it from the world.
  84977. removed[0].physicsBody = null;
  84978. }
  84979. }
  84980. };
  84981. /**
  84982. * Add a joint to the physics engine
  84983. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  84984. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  84985. * @param {PhysicsJoint} the joint that will connect both impostors.
  84986. */
  84987. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  84988. var impostorJoint = {
  84989. mainImpostor: mainImpostor,
  84990. connectedImpostor: connectedImpostor,
  84991. joint: joint
  84992. };
  84993. joint.physicsPlugin = this._physicsPlugin;
  84994. this._joints.push(impostorJoint);
  84995. this._physicsPlugin.generateJoint(impostorJoint);
  84996. };
  84997. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  84998. var matchingJoints = this._joints.filter(function (impostorJoint) {
  84999. return (impostorJoint.connectedImpostor === connectedImpostor
  85000. && impostorJoint.joint === joint
  85001. && impostorJoint.mainImpostor === mainImpostor);
  85002. });
  85003. if (matchingJoints.length) {
  85004. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85005. //TODO remove it from the list as well
  85006. }
  85007. };
  85008. /**
  85009. * Called by the scene. no need to call it.
  85010. */
  85011. PhysicsEngine.prototype._step = function (delta) {
  85012. var _this = this;
  85013. //check if any mesh has no body / requires an update
  85014. this._impostors.forEach(function (impostor) {
  85015. if (impostor.isBodyInitRequired()) {
  85016. _this._physicsPlugin.generatePhysicsBody(impostor);
  85017. }
  85018. });
  85019. if (delta > 0.1) {
  85020. delta = 0.1;
  85021. }
  85022. else if (delta <= 0) {
  85023. delta = 1.0 / 60.0;
  85024. }
  85025. this._physicsPlugin.executeStep(delta, this._impostors);
  85026. };
  85027. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85028. return this._physicsPlugin;
  85029. };
  85030. PhysicsEngine.prototype.getImpostors = function () {
  85031. return this._impostors;
  85032. };
  85033. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85034. for (var i = 0; i < this._impostors.length; ++i) {
  85035. if (this._impostors[i].object === object) {
  85036. return this._impostors[i];
  85037. }
  85038. }
  85039. return null;
  85040. };
  85041. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85042. for (var i = 0; i < this._impostors.length; ++i) {
  85043. if (this._impostors[i].physicsBody === body) {
  85044. return this._impostors[i];
  85045. }
  85046. }
  85047. return null;
  85048. };
  85049. // Statics
  85050. PhysicsEngine.Epsilon = 0.001;
  85051. return PhysicsEngine;
  85052. }());
  85053. BABYLON.PhysicsEngine = PhysicsEngine;
  85054. })(BABYLON || (BABYLON = {}));
  85055. //# sourceMappingURL=babylon.physicsEngine.js.map
  85056. var BABYLON;
  85057. (function (BABYLON) {
  85058. var PhysicsHelper = /** @class */ (function () {
  85059. function PhysicsHelper(scene) {
  85060. this._scene = scene;
  85061. this._physicsEngine = this._scene.getPhysicsEngine();
  85062. if (!this._physicsEngine) {
  85063. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85064. }
  85065. }
  85066. /**
  85067. * @param {Vector3} origin the origin of the explosion
  85068. * @param {number} radius the explosion radius
  85069. * @param {number} strength the explosion strength
  85070. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85071. */
  85072. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85073. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85074. if (!this._physicsEngine) {
  85075. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85076. return null;
  85077. }
  85078. var impostors = this._physicsEngine.getImpostors();
  85079. if (impostors.length === 0) {
  85080. return null;
  85081. }
  85082. var event = new PhysicsRadialExplosionEvent(this._scene);
  85083. impostors.forEach(function (impostor) {
  85084. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85085. if (!impostorForceAndContactPoint) {
  85086. return;
  85087. }
  85088. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85089. });
  85090. event.dispose(false);
  85091. return event;
  85092. };
  85093. /**
  85094. * @param {Vector3} origin the origin of the explosion
  85095. * @param {number} radius the explosion radius
  85096. * @param {number} strength the explosion strength
  85097. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85098. */
  85099. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85100. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85101. if (!this._physicsEngine) {
  85102. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85103. return null;
  85104. }
  85105. var impostors = this._physicsEngine.getImpostors();
  85106. if (impostors.length === 0) {
  85107. return null;
  85108. }
  85109. var event = new PhysicsRadialExplosionEvent(this._scene);
  85110. impostors.forEach(function (impostor) {
  85111. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85112. if (!impostorForceAndContactPoint) {
  85113. return;
  85114. }
  85115. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85116. });
  85117. event.dispose(false);
  85118. return event;
  85119. };
  85120. /**
  85121. * @param {Vector3} origin the origin of the explosion
  85122. * @param {number} radius the explosion radius
  85123. * @param {number} strength the explosion strength
  85124. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85125. */
  85126. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85127. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85128. if (!this._physicsEngine) {
  85129. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85130. return null;
  85131. }
  85132. var impostors = this._physicsEngine.getImpostors();
  85133. if (impostors.length === 0) {
  85134. return null;
  85135. }
  85136. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85137. event.dispose(false);
  85138. return event;
  85139. };
  85140. /**
  85141. * @param {Vector3} origin the origin of the updraft
  85142. * @param {number} radius the radius of the updraft
  85143. * @param {number} strength the strength of the updraft
  85144. * @param {number} height the height of the updraft
  85145. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85146. */
  85147. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85148. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85149. if (!this._physicsEngine) {
  85150. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85151. return null;
  85152. }
  85153. if (this._physicsEngine.getImpostors().length === 0) {
  85154. return null;
  85155. }
  85156. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85157. event.dispose(false);
  85158. return event;
  85159. };
  85160. /**
  85161. * @param {Vector3} origin the of the vortex
  85162. * @param {number} radius the radius of the vortex
  85163. * @param {number} strength the strength of the vortex
  85164. * @param {number} height the height of the vortex
  85165. */
  85166. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85167. if (!this._physicsEngine) {
  85168. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85169. return null;
  85170. }
  85171. if (this._physicsEngine.getImpostors().length === 0) {
  85172. return null;
  85173. }
  85174. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85175. event.dispose(false);
  85176. return event;
  85177. };
  85178. return PhysicsHelper;
  85179. }());
  85180. BABYLON.PhysicsHelper = PhysicsHelper;
  85181. /***** Radial explosion *****/
  85182. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85183. function PhysicsRadialExplosionEvent(scene) {
  85184. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85185. this._rays = [];
  85186. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85187. this._scene = scene;
  85188. }
  85189. /**
  85190. * Returns the data related to the radial explosion event (sphere & rays).
  85191. * @returns {PhysicsRadialExplosionEventData}
  85192. */
  85193. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85194. this._dataFetched = true;
  85195. return {
  85196. sphere: this._sphere,
  85197. rays: this._rays,
  85198. };
  85199. };
  85200. /**
  85201. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85202. * @param impostor
  85203. * @param {Vector3} origin the origin of the explosion
  85204. * @param {number} radius the explosion radius
  85205. * @param {number} strength the explosion strength
  85206. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85207. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85208. */
  85209. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85210. if (impostor.mass === 0) {
  85211. return null;
  85212. }
  85213. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85214. return null;
  85215. }
  85216. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85217. return null;
  85218. }
  85219. var impostorObjectCenter = impostor.getObjectCenter();
  85220. var direction = impostorObjectCenter.subtract(origin);
  85221. var ray = new BABYLON.Ray(origin, direction, radius);
  85222. this._rays.push(ray);
  85223. var hit = ray.intersectsMesh(impostor.object);
  85224. var contactPoint = hit.pickedPoint;
  85225. if (!contactPoint) {
  85226. return null;
  85227. }
  85228. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85229. if (distanceFromOrigin > radius) {
  85230. return null;
  85231. }
  85232. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85233. ? strength
  85234. : strength * (1 - (distanceFromOrigin / radius));
  85235. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85236. return { force: force, contactPoint: contactPoint };
  85237. };
  85238. /**
  85239. * Disposes the sphere.
  85240. * @param {bolean} force
  85241. */
  85242. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85243. var _this = this;
  85244. if (force === void 0) { force = true; }
  85245. if (force) {
  85246. this._sphere.dispose();
  85247. }
  85248. else {
  85249. setTimeout(function () {
  85250. if (!_this._dataFetched) {
  85251. _this._sphere.dispose();
  85252. }
  85253. }, 0);
  85254. }
  85255. };
  85256. /*** Helpers ***/
  85257. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85258. if (!this._sphere) {
  85259. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85260. this._sphere.isVisible = false;
  85261. }
  85262. };
  85263. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85264. var impostorObject = impostor.object;
  85265. this._prepareSphere();
  85266. this._sphere.position = origin;
  85267. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85268. this._sphere._updateBoundingInfo();
  85269. this._sphere.computeWorldMatrix(true);
  85270. return this._sphere.intersectsMesh(impostorObject, true);
  85271. };
  85272. return PhysicsRadialExplosionEvent;
  85273. }());
  85274. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85275. /***** Gravitational Field *****/
  85276. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85277. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85278. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85279. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85280. this._physicsHelper = physicsHelper;
  85281. this._scene = scene;
  85282. this._origin = origin;
  85283. this._radius = radius;
  85284. this._strength = strength;
  85285. this._falloff = falloff;
  85286. this._tickCallback = this._tick.bind(this);
  85287. }
  85288. /**
  85289. * Returns the data related to the gravitational field event (sphere).
  85290. * @returns {PhysicsGravitationalFieldEventData}
  85291. */
  85292. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85293. this._dataFetched = true;
  85294. return {
  85295. sphere: this._sphere,
  85296. };
  85297. };
  85298. /**
  85299. * Enables the gravitational field.
  85300. */
  85301. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85302. this._tickCallback.call(this);
  85303. this._scene.registerBeforeRender(this._tickCallback);
  85304. };
  85305. /**
  85306. * Disables the gravitational field.
  85307. */
  85308. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85309. this._scene.unregisterBeforeRender(this._tickCallback);
  85310. };
  85311. /**
  85312. * Disposes the sphere.
  85313. * @param {bolean} force
  85314. */
  85315. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85316. var _this = this;
  85317. if (force === void 0) { force = true; }
  85318. if (force) {
  85319. this._sphere.dispose();
  85320. }
  85321. else {
  85322. setTimeout(function () {
  85323. if (!_this._dataFetched) {
  85324. _this._sphere.dispose();
  85325. }
  85326. }, 0);
  85327. }
  85328. };
  85329. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85330. // Since the params won't change, we fetch the event only once
  85331. if (this._sphere) {
  85332. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85333. }
  85334. else {
  85335. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85336. if (radialExplosionEvent) {
  85337. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85338. }
  85339. }
  85340. };
  85341. return PhysicsGravitationalFieldEvent;
  85342. }());
  85343. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85344. /***** Updraft *****/
  85345. var PhysicsUpdraftEvent = /** @class */ (function () {
  85346. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85347. this._scene = _scene;
  85348. this._origin = _origin;
  85349. this._radius = _radius;
  85350. this._strength = _strength;
  85351. this._height = _height;
  85352. this._updraftMode = _updraftMode;
  85353. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85354. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85355. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85356. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85357. this._physicsEngine = this._scene.getPhysicsEngine();
  85358. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85359. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85360. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85361. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85362. }
  85363. this._tickCallback = this._tick.bind(this);
  85364. }
  85365. /**
  85366. * Returns the data related to the updraft event (cylinder).
  85367. * @returns {PhysicsUpdraftEventData}
  85368. */
  85369. PhysicsUpdraftEvent.prototype.getData = function () {
  85370. this._dataFetched = true;
  85371. return {
  85372. cylinder: this._cylinder,
  85373. };
  85374. };
  85375. /**
  85376. * Enables the updraft.
  85377. */
  85378. PhysicsUpdraftEvent.prototype.enable = function () {
  85379. this._tickCallback.call(this);
  85380. this._scene.registerBeforeRender(this._tickCallback);
  85381. };
  85382. /**
  85383. * Disables the cortex.
  85384. */
  85385. PhysicsUpdraftEvent.prototype.disable = function () {
  85386. this._scene.unregisterBeforeRender(this._tickCallback);
  85387. };
  85388. /**
  85389. * Disposes the sphere.
  85390. * @param {bolean} force
  85391. */
  85392. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85393. var _this = this;
  85394. if (force === void 0) { force = true; }
  85395. if (force) {
  85396. this._cylinder.dispose();
  85397. }
  85398. else {
  85399. setTimeout(function () {
  85400. if (!_this._dataFetched) {
  85401. _this._cylinder.dispose();
  85402. }
  85403. }, 0);
  85404. }
  85405. };
  85406. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85407. if (impostor.mass === 0) {
  85408. return null;
  85409. }
  85410. if (!this._intersectsWithCylinder(impostor)) {
  85411. return null;
  85412. }
  85413. var impostorObjectCenter = impostor.getObjectCenter();
  85414. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85415. var direction = this._originDirection;
  85416. }
  85417. else {
  85418. var direction = impostorObjectCenter.subtract(this._originTop);
  85419. }
  85420. var multiplier = this._strength * -1;
  85421. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85422. return { force: force, contactPoint: impostorObjectCenter };
  85423. };
  85424. PhysicsUpdraftEvent.prototype._tick = function () {
  85425. var _this = this;
  85426. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85427. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85428. if (!impostorForceAndContactPoint) {
  85429. return;
  85430. }
  85431. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85432. });
  85433. };
  85434. /*** Helpers ***/
  85435. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85436. if (!this._cylinder) {
  85437. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85438. height: this._height,
  85439. diameter: this._radius * 2,
  85440. }, this._scene);
  85441. this._cylinder.isVisible = false;
  85442. }
  85443. };
  85444. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85445. var impostorObject = impostor.object;
  85446. this._prepareCylinder();
  85447. this._cylinder.position = this._cylinderPosition;
  85448. return this._cylinder.intersectsMesh(impostorObject, true);
  85449. };
  85450. return PhysicsUpdraftEvent;
  85451. }());
  85452. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85453. /***** Vortex *****/
  85454. var PhysicsVortexEvent = /** @class */ (function () {
  85455. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85456. this._scene = _scene;
  85457. this._origin = _origin;
  85458. this._radius = _radius;
  85459. this._strength = _strength;
  85460. this._height = _height;
  85461. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85462. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85463. this._updraftMultiplier = 0.02;
  85464. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85465. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85466. this._physicsEngine = this._scene.getPhysicsEngine();
  85467. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85468. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85469. this._tickCallback = this._tick.bind(this);
  85470. }
  85471. /**
  85472. * Returns the data related to the vortex event (cylinder).
  85473. * @returns {PhysicsVortexEventData}
  85474. */
  85475. PhysicsVortexEvent.prototype.getData = function () {
  85476. this._dataFetched = true;
  85477. return {
  85478. cylinder: this._cylinder,
  85479. };
  85480. };
  85481. /**
  85482. * Enables the vortex.
  85483. */
  85484. PhysicsVortexEvent.prototype.enable = function () {
  85485. this._tickCallback.call(this);
  85486. this._scene.registerBeforeRender(this._tickCallback);
  85487. };
  85488. /**
  85489. * Disables the cortex.
  85490. */
  85491. PhysicsVortexEvent.prototype.disable = function () {
  85492. this._scene.unregisterBeforeRender(this._tickCallback);
  85493. };
  85494. /**
  85495. * Disposes the sphere.
  85496. * @param {bolean} force
  85497. */
  85498. PhysicsVortexEvent.prototype.dispose = function (force) {
  85499. var _this = this;
  85500. if (force === void 0) { force = true; }
  85501. if (force) {
  85502. this._cylinder.dispose();
  85503. }
  85504. else {
  85505. setTimeout(function () {
  85506. if (!_this._dataFetched) {
  85507. _this._cylinder.dispose();
  85508. }
  85509. }, 0);
  85510. }
  85511. };
  85512. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85513. if (impostor.mass === 0) {
  85514. return null;
  85515. }
  85516. if (!this._intersectsWithCylinder(impostor)) {
  85517. return null;
  85518. }
  85519. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85520. return null;
  85521. }
  85522. var impostorObjectCenter = impostor.getObjectCenter();
  85523. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  85524. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85525. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85526. var hit = ray.intersectsMesh(impostor.object);
  85527. var contactPoint = hit.pickedPoint;
  85528. if (!contactPoint) {
  85529. return null;
  85530. }
  85531. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85532. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85533. var directionToOrigin = contactPoint.normalize();
  85534. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85535. directionToOrigin = directionToOrigin.negate();
  85536. }
  85537. // TODO: find a more physically based solution
  85538. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85539. var forceX = directionToOrigin.x * this._strength / 8;
  85540. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85541. var forceZ = directionToOrigin.z * this._strength / 8;
  85542. }
  85543. else {
  85544. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85545. var forceY = this._originTop.y * this._updraftMultiplier;
  85546. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85547. }
  85548. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85549. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85550. return { force: force, contactPoint: impostorObjectCenter };
  85551. };
  85552. PhysicsVortexEvent.prototype._tick = function () {
  85553. var _this = this;
  85554. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85555. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85556. if (!impostorForceAndContactPoint) {
  85557. return;
  85558. }
  85559. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85560. });
  85561. };
  85562. /*** Helpers ***/
  85563. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85564. if (!this._cylinder) {
  85565. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85566. height: this._height,
  85567. diameter: this._radius * 2,
  85568. }, this._scene);
  85569. this._cylinder.isVisible = false;
  85570. }
  85571. };
  85572. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85573. var impostorObject = impostor.object;
  85574. this._prepareCylinder();
  85575. this._cylinder.position = this._cylinderPosition;
  85576. return this._cylinder.intersectsMesh(impostorObject, true);
  85577. };
  85578. return PhysicsVortexEvent;
  85579. }());
  85580. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85581. /***** Enums *****/
  85582. /**
  85583. * The strenght of the force in correspondence to the distance of the affected object
  85584. */
  85585. var PhysicsRadialImpulseFalloff;
  85586. (function (PhysicsRadialImpulseFalloff) {
  85587. /** Defines that impulse is constant in strength across it's whole radius */
  85588. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85589. /** DEfines that impulse gets weaker if it's further from the origin */
  85590. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85591. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85592. /**
  85593. * The strenght of the force in correspondence to the distance of the affected object
  85594. */
  85595. var PhysicsUpdraftMode;
  85596. (function (PhysicsUpdraftMode) {
  85597. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85598. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85599. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85600. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85601. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85602. })(BABYLON || (BABYLON = {}));
  85603. //# sourceMappingURL=babylon.physicsHelper.js.map
  85604. var BABYLON;
  85605. (function (BABYLON) {
  85606. var CannonJSPlugin = /** @class */ (function () {
  85607. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85608. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85609. if (iterations === void 0) { iterations = 10; }
  85610. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85611. this.name = "CannonJSPlugin";
  85612. this._physicsMaterials = new Array();
  85613. this._fixedTimeStep = 1 / 60;
  85614. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85615. this.BJSCANNON = CANNON;
  85616. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85617. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85618. this._tmpPosition = BABYLON.Vector3.Zero();
  85619. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85620. this._tmpUnityRotation = new BABYLON.Quaternion();
  85621. if (!this.isSupported()) {
  85622. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85623. return;
  85624. }
  85625. this._extendNamespace();
  85626. this.world = new this.BJSCANNON.World();
  85627. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85628. this.world.solver.iterations = iterations;
  85629. }
  85630. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85631. this.world.gravity.copy(gravity);
  85632. };
  85633. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85634. this._fixedTimeStep = timeStep;
  85635. };
  85636. CannonJSPlugin.prototype.getTimeStep = function () {
  85637. return this._fixedTimeStep;
  85638. };
  85639. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85640. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85641. };
  85642. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85643. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85644. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85645. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85646. };
  85647. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85648. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85649. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85650. impostor.physicsBody.applyForce(impulse, worldPoint);
  85651. };
  85652. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85653. //parent-child relationship. Does this impostor has a parent impostor?
  85654. if (impostor.parent) {
  85655. if (impostor.physicsBody) {
  85656. this.removePhysicsBody(impostor);
  85657. //TODO is that needed?
  85658. impostor.forceUpdate();
  85659. }
  85660. return;
  85661. }
  85662. //should a new body be created for this impostor?
  85663. if (impostor.isBodyInitRequired()) {
  85664. var shape = this._createShape(impostor);
  85665. //unregister events, if body is being changed
  85666. var oldBody = impostor.physicsBody;
  85667. if (oldBody) {
  85668. this.removePhysicsBody(impostor);
  85669. }
  85670. //create the body and material
  85671. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85672. var bodyCreationObject = {
  85673. mass: impostor.getParam("mass"),
  85674. material: material
  85675. };
  85676. // A simple extend, in case native options were used.
  85677. var nativeOptions = impostor.getParam("nativeOptions");
  85678. for (var key in nativeOptions) {
  85679. if (nativeOptions.hasOwnProperty(key)) {
  85680. bodyCreationObject[key] = nativeOptions[key];
  85681. }
  85682. }
  85683. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85684. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85685. this.world.addEventListener("preStep", impostor.beforeStep);
  85686. this.world.addEventListener("postStep", impostor.afterStep);
  85687. impostor.physicsBody.addShape(shape);
  85688. this.world.add(impostor.physicsBody);
  85689. //try to keep the body moving in the right direction by taking old properties.
  85690. //Should be tested!
  85691. if (oldBody) {
  85692. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85693. impostor.physicsBody[param].copy(oldBody[param]);
  85694. });
  85695. }
  85696. this._processChildMeshes(impostor);
  85697. }
  85698. //now update the body's transformation
  85699. this._updatePhysicsBodyTransformation(impostor);
  85700. };
  85701. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85702. var _this = this;
  85703. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85704. var currentRotation = mainImpostor.object.rotationQuaternion;
  85705. if (meshChildren.length) {
  85706. var processMesh = function (localPosition, mesh) {
  85707. if (!currentRotation || !mesh.rotationQuaternion) {
  85708. return;
  85709. }
  85710. var childImpostor = mesh.getPhysicsImpostor();
  85711. if (childImpostor) {
  85712. var parent = childImpostor.parent;
  85713. if (parent !== mainImpostor) {
  85714. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85715. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85716. if (childImpostor.physicsBody) {
  85717. _this.removePhysicsBody(childImpostor);
  85718. childImpostor.physicsBody = null;
  85719. }
  85720. childImpostor.parent = mainImpostor;
  85721. childImpostor.resetUpdateFlags();
  85722. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
  85723. //Add the mass of the children.
  85724. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85725. }
  85726. }
  85727. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85728. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85729. };
  85730. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85731. }
  85732. };
  85733. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85734. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85735. this.world.removeEventListener("preStep", impostor.beforeStep);
  85736. this.world.removeEventListener("postStep", impostor.afterStep);
  85737. this.world.remove(impostor.physicsBody);
  85738. };
  85739. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85740. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85741. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85742. if (!mainBody || !connectedBody) {
  85743. return;
  85744. }
  85745. var constraint;
  85746. var jointData = impostorJoint.joint.jointData;
  85747. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85748. var constraintData = {
  85749. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85750. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85751. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85752. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85753. maxForce: jointData.nativeParams.maxForce,
  85754. collideConnected: !!jointData.collision
  85755. };
  85756. switch (impostorJoint.joint.type) {
  85757. case BABYLON.PhysicsJoint.HingeJoint:
  85758. case BABYLON.PhysicsJoint.Hinge2Joint:
  85759. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85760. break;
  85761. case BABYLON.PhysicsJoint.DistanceJoint:
  85762. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85763. break;
  85764. case BABYLON.PhysicsJoint.SpringJoint:
  85765. var springData = jointData;
  85766. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85767. restLength: springData.length,
  85768. stiffness: springData.stiffness,
  85769. damping: springData.damping,
  85770. localAnchorA: constraintData.pivotA,
  85771. localAnchorB: constraintData.pivotB
  85772. });
  85773. break;
  85774. case BABYLON.PhysicsJoint.LockJoint:
  85775. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85776. break;
  85777. case BABYLON.PhysicsJoint.PointToPointJoint:
  85778. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85779. default:
  85780. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85781. break;
  85782. }
  85783. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85784. constraint.collideConnected = !!jointData.collision;
  85785. impostorJoint.joint.physicsJoint = constraint;
  85786. //don't add spring as constraint, as it is not one.
  85787. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85788. this.world.addConstraint(constraint);
  85789. }
  85790. else {
  85791. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85792. constraint.applyForce();
  85793. });
  85794. }
  85795. };
  85796. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85797. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85798. };
  85799. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85800. var index;
  85801. var mat;
  85802. for (index = 0; index < this._physicsMaterials.length; index++) {
  85803. mat = this._physicsMaterials[index];
  85804. if (mat.friction === friction && mat.restitution === restitution) {
  85805. return mat;
  85806. }
  85807. }
  85808. var currentMat = new this.BJSCANNON.Material(name);
  85809. currentMat.friction = friction;
  85810. currentMat.restitution = restitution;
  85811. this._physicsMaterials.push(currentMat);
  85812. return currentMat;
  85813. };
  85814. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85815. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85816. };
  85817. CannonJSPlugin.prototype._createShape = function (impostor) {
  85818. var object = impostor.object;
  85819. var returnValue;
  85820. var extendSize = impostor.getObjectExtendSize();
  85821. switch (impostor.type) {
  85822. case BABYLON.PhysicsImpostor.SphereImpostor:
  85823. var radiusX = extendSize.x;
  85824. var radiusY = extendSize.y;
  85825. var radiusZ = extendSize.z;
  85826. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85827. break;
  85828. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85829. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85830. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85831. break;
  85832. case BABYLON.PhysicsImpostor.BoxImpostor:
  85833. var box = extendSize.scale(0.5);
  85834. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85835. break;
  85836. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85837. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85838. returnValue = new this.BJSCANNON.Plane();
  85839. break;
  85840. case BABYLON.PhysicsImpostor.MeshImpostor:
  85841. // should transform the vertex data to world coordinates!!
  85842. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85843. var rawFaces = object.getIndices ? object.getIndices() : [];
  85844. if (!rawVerts)
  85845. return;
  85846. // get only scale! so the object could transform correctly.
  85847. var oldPosition = object.position.clone();
  85848. var oldRotation = object.rotation && object.rotation.clone();
  85849. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85850. object.position.copyFromFloats(0, 0, 0);
  85851. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85852. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85853. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85854. var transform = object.computeWorldMatrix(true);
  85855. // convert rawVerts to object space
  85856. var temp = new Array();
  85857. var index;
  85858. for (index = 0; index < rawVerts.length; index += 3) {
  85859. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  85860. }
  85861. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  85862. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  85863. //now set back the transformation!
  85864. object.position.copyFrom(oldPosition);
  85865. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  85866. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  85867. break;
  85868. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  85869. var oldPosition2 = object.position.clone();
  85870. var oldRotation2 = object.rotation && object.rotation.clone();
  85871. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  85872. object.position.copyFromFloats(0, 0, 0);
  85873. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85874. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85875. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85876. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  85877. returnValue = this._createHeightmap(object);
  85878. object.position.copyFrom(oldPosition2);
  85879. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  85880. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  85881. object.computeWorldMatrix(true);
  85882. break;
  85883. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85884. returnValue = new this.BJSCANNON.Particle();
  85885. break;
  85886. }
  85887. return returnValue;
  85888. };
  85889. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  85890. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85891. var transform = object.computeWorldMatrix(true);
  85892. // convert rawVerts to object space
  85893. var temp = new Array();
  85894. var index;
  85895. for (index = 0; index < pos.length; index += 3) {
  85896. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  85897. }
  85898. pos = temp;
  85899. var matrix = new Array();
  85900. //For now pointDepth will not be used and will be automatically calculated.
  85901. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  85902. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  85903. var boundingInfo = object.getBoundingInfo();
  85904. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  85905. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  85906. var elementSize = dim * 2 / arraySize;
  85907. for (var i = 0; i < pos.length; i = i + 3) {
  85908. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  85909. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  85910. var y = -pos[i + 2] + minY;
  85911. if (!matrix[x]) {
  85912. matrix[x] = [];
  85913. }
  85914. if (!matrix[x][z]) {
  85915. matrix[x][z] = y;
  85916. }
  85917. matrix[x][z] = Math.max(y, matrix[x][z]);
  85918. }
  85919. for (var x = 0; x <= arraySize; ++x) {
  85920. if (!matrix[x]) {
  85921. var loc = 1;
  85922. while (!matrix[(x + loc) % arraySize]) {
  85923. loc++;
  85924. }
  85925. matrix[x] = matrix[(x + loc) % arraySize].slice();
  85926. //console.log("missing x", x);
  85927. }
  85928. for (var z = 0; z <= arraySize; ++z) {
  85929. if (!matrix[x][z]) {
  85930. var loc = 1;
  85931. var newValue;
  85932. while (newValue === undefined) {
  85933. newValue = matrix[x][(z + loc++) % arraySize];
  85934. }
  85935. matrix[x][z] = newValue;
  85936. }
  85937. }
  85938. }
  85939. var shape = new this.BJSCANNON.Heightfield(matrix, {
  85940. elementSize: elementSize
  85941. });
  85942. //For future reference, needed for body transformation
  85943. shape.minY = minY;
  85944. return shape;
  85945. };
  85946. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  85947. var object = impostor.object;
  85948. //make sure it is updated...
  85949. object.computeWorldMatrix && object.computeWorldMatrix(true);
  85950. // The delta between the mesh position and the mesh bounding box center
  85951. var bInfo = object.getBoundingInfo();
  85952. if (!bInfo)
  85953. return;
  85954. var center = impostor.getObjectCenter();
  85955. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  85956. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  85957. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  85958. this._tmpPosition.copyFrom(center);
  85959. var quaternion = object.rotationQuaternion;
  85960. if (!quaternion) {
  85961. return;
  85962. }
  85963. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  85964. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  85965. //-90 DEG in X, precalculated
  85966. quaternion = quaternion.multiply(this._minus90X);
  85967. //Invert! (Precalculated, 90 deg in X)
  85968. //No need to clone. this will never change.
  85969. impostor.setDeltaRotation(this._plus90X);
  85970. }
  85971. //If it is a heightfield, if should be centered.
  85972. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  85973. var mesh = object;
  85974. var boundingInfo = mesh.getBoundingInfo();
  85975. //calculate the correct body position:
  85976. var rotationQuaternion = mesh.rotationQuaternion;
  85977. mesh.rotationQuaternion = this._tmpUnityRotation;
  85978. mesh.computeWorldMatrix(true);
  85979. //get original center with no rotation
  85980. var c = center.clone();
  85981. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  85982. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  85983. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  85984. mesh.setPreTransformMatrix(p);
  85985. mesh.computeWorldMatrix(true);
  85986. //calculate the translation
  85987. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  85988. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  85989. //add it inverted to the delta
  85990. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  85991. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  85992. //rotation is back
  85993. mesh.rotationQuaternion = rotationQuaternion;
  85994. mesh.setPreTransformMatrix(oldPivot);
  85995. mesh.computeWorldMatrix(true);
  85996. }
  85997. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  85998. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  85999. //this._tmpPosition.copyFrom(object.position);
  86000. }
  86001. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86002. //Now update the impostor object
  86003. impostor.physicsBody.position.copy(this._tmpPosition);
  86004. impostor.physicsBody.quaternion.copy(quaternion);
  86005. };
  86006. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86007. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86008. if (impostor.object.rotationQuaternion) {
  86009. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86010. }
  86011. };
  86012. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86013. impostor.physicsBody.position.copy(newPosition);
  86014. impostor.physicsBody.quaternion.copy(newRotation);
  86015. };
  86016. CannonJSPlugin.prototype.isSupported = function () {
  86017. return this.BJSCANNON !== undefined;
  86018. };
  86019. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86020. impostor.physicsBody.velocity.copy(velocity);
  86021. };
  86022. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86023. impostor.physicsBody.angularVelocity.copy(velocity);
  86024. };
  86025. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86026. var v = impostor.physicsBody.velocity;
  86027. if (!v) {
  86028. return null;
  86029. }
  86030. return new BABYLON.Vector3(v.x, v.y, v.z);
  86031. };
  86032. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86033. var v = impostor.physicsBody.angularVelocity;
  86034. if (!v) {
  86035. return null;
  86036. }
  86037. return new BABYLON.Vector3(v.x, v.y, v.z);
  86038. };
  86039. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86040. impostor.physicsBody.mass = mass;
  86041. impostor.physicsBody.updateMassProperties();
  86042. };
  86043. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86044. return impostor.physicsBody.mass;
  86045. };
  86046. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86047. return impostor.physicsBody.material.friction;
  86048. };
  86049. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86050. impostor.physicsBody.material.friction = friction;
  86051. };
  86052. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86053. return impostor.physicsBody.material.restitution;
  86054. };
  86055. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86056. impostor.physicsBody.material.restitution = restitution;
  86057. };
  86058. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86059. impostor.physicsBody.sleep();
  86060. };
  86061. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86062. impostor.physicsBody.wakeUp();
  86063. };
  86064. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86065. joint.physicsJoint.distance = maxDistance;
  86066. };
  86067. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86068. // if (!motorIndex) {
  86069. // joint.physicsJoint.enableMotor();
  86070. // }
  86071. // }
  86072. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86073. // if (!motorIndex) {
  86074. // joint.physicsJoint.disableMotor();
  86075. // }
  86076. // }
  86077. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86078. if (!motorIndex) {
  86079. joint.physicsJoint.enableMotor();
  86080. joint.physicsJoint.setMotorSpeed(speed);
  86081. if (maxForce) {
  86082. this.setLimit(joint, maxForce);
  86083. }
  86084. }
  86085. };
  86086. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86087. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86088. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86089. };
  86090. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86091. var body = impostor.physicsBody;
  86092. mesh.position.x = body.position.x;
  86093. mesh.position.y = body.position.y;
  86094. mesh.position.z = body.position.z;
  86095. if (mesh.rotationQuaternion) {
  86096. mesh.rotationQuaternion.x = body.quaternion.x;
  86097. mesh.rotationQuaternion.y = body.quaternion.y;
  86098. mesh.rotationQuaternion.z = body.quaternion.z;
  86099. mesh.rotationQuaternion.w = body.quaternion.w;
  86100. }
  86101. };
  86102. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86103. var shape = impostor.physicsBody.shapes[0];
  86104. return shape.boundingSphereRadius;
  86105. };
  86106. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86107. var shape = impostor.physicsBody.shapes[0];
  86108. result.x = shape.halfExtents.x * 2;
  86109. result.y = shape.halfExtents.y * 2;
  86110. result.z = shape.halfExtents.z * 2;
  86111. };
  86112. CannonJSPlugin.prototype.dispose = function () {
  86113. };
  86114. CannonJSPlugin.prototype._extendNamespace = function () {
  86115. //this will force cannon to execute at least one step when using interpolation
  86116. var step_tmp1 = new this.BJSCANNON.Vec3();
  86117. var Engine = this.BJSCANNON;
  86118. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86119. maxSubSteps = maxSubSteps || 10;
  86120. timeSinceLastCalled = timeSinceLastCalled || 0;
  86121. if (timeSinceLastCalled === 0) {
  86122. this.internalStep(dt);
  86123. this.time += dt;
  86124. }
  86125. else {
  86126. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86127. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86128. var t0 = performance.now();
  86129. for (var i = 0; i !== internalSteps; i++) {
  86130. this.internalStep(dt);
  86131. if (performance.now() - t0 > dt * 1000) {
  86132. break;
  86133. }
  86134. }
  86135. this.time += timeSinceLastCalled;
  86136. var h = this.time % dt;
  86137. var h_div_dt = h / dt;
  86138. var interpvelo = step_tmp1;
  86139. var bodies = this.bodies;
  86140. for (var j = 0; j !== bodies.length; j++) {
  86141. var b = bodies[j];
  86142. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86143. b.position.vsub(b.previousPosition, interpvelo);
  86144. interpvelo.scale(h_div_dt, interpvelo);
  86145. b.position.vadd(interpvelo, b.interpolatedPosition);
  86146. }
  86147. else {
  86148. b.interpolatedPosition.copy(b.position);
  86149. b.interpolatedQuaternion.copy(b.quaternion);
  86150. }
  86151. }
  86152. }
  86153. };
  86154. };
  86155. return CannonJSPlugin;
  86156. }());
  86157. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86158. })(BABYLON || (BABYLON = {}));
  86159. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86160. var BABYLON;
  86161. (function (BABYLON) {
  86162. var OimoJSPlugin = /** @class */ (function () {
  86163. function OimoJSPlugin(iterations) {
  86164. this.name = "OimoJSPlugin";
  86165. this._tmpImpostorsArray = [];
  86166. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86167. this.BJSOIMO = OIMO;
  86168. this.world = new this.BJSOIMO.World({
  86169. iterations: iterations
  86170. });
  86171. this.world.clear();
  86172. }
  86173. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86174. this.world.gravity.copy(gravity);
  86175. };
  86176. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86177. this.world.timeStep = timeStep;
  86178. };
  86179. OimoJSPlugin.prototype.getTimeStep = function () {
  86180. return this.world.timeStep;
  86181. };
  86182. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86183. var _this = this;
  86184. impostors.forEach(function (impostor) {
  86185. impostor.beforeStep();
  86186. });
  86187. this.world.step();
  86188. impostors.forEach(function (impostor) {
  86189. impostor.afterStep();
  86190. //update the ordered impostors array
  86191. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86192. });
  86193. //check for collisions
  86194. var contact = this.world.contacts;
  86195. while (contact !== null) {
  86196. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86197. contact = contact.next;
  86198. continue;
  86199. }
  86200. //is this body colliding with any other? get the impostor
  86201. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86202. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86203. if (!mainImpostor || !collidingImpostor) {
  86204. contact = contact.next;
  86205. continue;
  86206. }
  86207. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86208. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86209. contact = contact.next;
  86210. }
  86211. };
  86212. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86213. var mass = impostor.physicsBody.mass;
  86214. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86215. };
  86216. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86217. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86218. this.applyImpulse(impostor, force, contactPoint);
  86219. };
  86220. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86221. var _this = this;
  86222. //parent-child relationship. Does this impostor has a parent impostor?
  86223. if (impostor.parent) {
  86224. if (impostor.physicsBody) {
  86225. this.removePhysicsBody(impostor);
  86226. //TODO is that needed?
  86227. impostor.forceUpdate();
  86228. }
  86229. return;
  86230. }
  86231. if (impostor.isBodyInitRequired()) {
  86232. var bodyConfig = {
  86233. name: impostor.uniqueId,
  86234. //Oimo must have mass, also for static objects.
  86235. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86236. size: [],
  86237. type: [],
  86238. pos: [],
  86239. posShape: [],
  86240. rot: [],
  86241. rotShape: [],
  86242. move: impostor.getParam("mass") !== 0,
  86243. density: impostor.getParam("mass"),
  86244. friction: impostor.getParam("friction"),
  86245. restitution: impostor.getParam("restitution"),
  86246. //Supporting older versions of Oimo
  86247. world: this.world
  86248. };
  86249. var impostors = [impostor];
  86250. var addToArray = function (parent) {
  86251. if (!parent.getChildMeshes)
  86252. return;
  86253. parent.getChildMeshes().forEach(function (m) {
  86254. if (m.physicsImpostor) {
  86255. impostors.push(m.physicsImpostor);
  86256. //m.physicsImpostor._init();
  86257. }
  86258. });
  86259. };
  86260. addToArray(impostor.object);
  86261. var checkWithEpsilon_1 = function (value) {
  86262. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86263. };
  86264. impostors.forEach(function (i) {
  86265. if (!i.object.rotationQuaternion) {
  86266. return;
  86267. }
  86268. //get the correct bounding box
  86269. var oldQuaternion = i.object.rotationQuaternion;
  86270. var rot = oldQuaternion.toEulerAngles();
  86271. var extendSize = i.getObjectExtendSize();
  86272. var radToDeg = 57.295779513082320876;
  86273. if (i === impostor) {
  86274. var center = impostor.getObjectCenter();
  86275. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86276. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86277. //Can also use Array.prototype.push.apply
  86278. bodyConfig.pos.push(center.x);
  86279. bodyConfig.pos.push(center.y);
  86280. bodyConfig.pos.push(center.z);
  86281. bodyConfig.posShape.push(0, 0, 0);
  86282. //tmp solution
  86283. bodyConfig.rot.push(rot.x * radToDeg);
  86284. bodyConfig.rot.push(rot.y * radToDeg);
  86285. bodyConfig.rot.push(rot.z * radToDeg);
  86286. bodyConfig.rotShape.push(0, 0, 0);
  86287. }
  86288. else {
  86289. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86290. bodyConfig.posShape.push(localPosition.x);
  86291. bodyConfig.posShape.push(localPosition.y);
  86292. bodyConfig.posShape.push(localPosition.z);
  86293. bodyConfig.pos.push(0, 0, 0);
  86294. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86295. bodyConfig.rot.push(0);
  86296. bodyConfig.rot.push(0);
  86297. bodyConfig.rot.push(0);
  86298. bodyConfig.rotShape.push(rot.x * radToDeg);
  86299. bodyConfig.rotShape.push(rot.y * radToDeg);
  86300. bodyConfig.rotShape.push(rot.z * radToDeg);
  86301. }
  86302. // register mesh
  86303. switch (i.type) {
  86304. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86305. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86306. case BABYLON.PhysicsImpostor.SphereImpostor:
  86307. var radiusX = extendSize.x;
  86308. var radiusY = extendSize.y;
  86309. var radiusZ = extendSize.z;
  86310. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86311. bodyConfig.type.push('sphere');
  86312. //due to the way oimo works with compounds, add 3 times
  86313. bodyConfig.size.push(size);
  86314. bodyConfig.size.push(size);
  86315. bodyConfig.size.push(size);
  86316. break;
  86317. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86318. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86319. var sizeY = checkWithEpsilon_1(extendSize.y);
  86320. bodyConfig.type.push('cylinder');
  86321. bodyConfig.size.push(sizeX);
  86322. bodyConfig.size.push(sizeY);
  86323. //due to the way oimo works with compounds, add one more value.
  86324. bodyConfig.size.push(sizeY);
  86325. break;
  86326. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86327. case BABYLON.PhysicsImpostor.BoxImpostor:
  86328. default:
  86329. var sizeX = checkWithEpsilon_1(extendSize.x);
  86330. var sizeY = checkWithEpsilon_1(extendSize.y);
  86331. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86332. bodyConfig.type.push('box');
  86333. //if (i === impostor) {
  86334. bodyConfig.size.push(sizeX);
  86335. bodyConfig.size.push(sizeY);
  86336. bodyConfig.size.push(sizeZ);
  86337. //} else {
  86338. // bodyConfig.size.push(0,0,0);
  86339. //}
  86340. break;
  86341. }
  86342. //actually not needed, but hey...
  86343. i.object.rotationQuaternion = oldQuaternion;
  86344. });
  86345. impostor.physicsBody = this.world.add(bodyConfig);
  86346. }
  86347. else {
  86348. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86349. }
  86350. impostor.setDeltaPosition(this._tmpPositionVector);
  86351. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86352. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86353. };
  86354. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86355. //impostor.physicsBody.dispose();
  86356. //Same as : (older oimo versions)
  86357. this.world.removeRigidBody(impostor.physicsBody);
  86358. };
  86359. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86360. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86361. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86362. if (!mainBody || !connectedBody) {
  86363. return;
  86364. }
  86365. var jointData = impostorJoint.joint.jointData;
  86366. var options = jointData.nativeParams || {};
  86367. var type;
  86368. var nativeJointData = {
  86369. body1: mainBody,
  86370. body2: connectedBody,
  86371. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86372. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86373. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86374. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86375. min: options.min,
  86376. max: options.max,
  86377. collision: options.collision || jointData.collision,
  86378. spring: options.spring,
  86379. //supporting older version of Oimo
  86380. world: this.world
  86381. };
  86382. switch (impostorJoint.joint.type) {
  86383. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86384. type = "jointBall";
  86385. break;
  86386. case BABYLON.PhysicsJoint.SpringJoint:
  86387. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86388. var springData = jointData;
  86389. nativeJointData.min = springData.length || nativeJointData.min;
  86390. //Max should also be set, just make sure it is at least min
  86391. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86392. case BABYLON.PhysicsJoint.DistanceJoint:
  86393. type = "jointDistance";
  86394. nativeJointData.max = jointData.maxDistance;
  86395. break;
  86396. case BABYLON.PhysicsJoint.PrismaticJoint:
  86397. type = "jointPrisme";
  86398. break;
  86399. case BABYLON.PhysicsJoint.SliderJoint:
  86400. type = "jointSlide";
  86401. break;
  86402. case BABYLON.PhysicsJoint.WheelJoint:
  86403. type = "jointWheel";
  86404. break;
  86405. case BABYLON.PhysicsJoint.HingeJoint:
  86406. default:
  86407. type = "jointHinge";
  86408. break;
  86409. }
  86410. nativeJointData.type = type;
  86411. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86412. };
  86413. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86414. //Bug in Oimo prevents us from disposing a joint in the playground
  86415. //joint.joint.physicsJoint.dispose();
  86416. //So we will bruteforce it!
  86417. try {
  86418. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86419. }
  86420. catch (e) {
  86421. BABYLON.Tools.Warn(e);
  86422. }
  86423. };
  86424. OimoJSPlugin.prototype.isSupported = function () {
  86425. return this.BJSOIMO !== undefined;
  86426. };
  86427. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86428. if (!impostor.physicsBody.sleeping) {
  86429. //TODO check that
  86430. /*if (impostor.physicsBody.shapes.next) {
  86431. var parentShape = this._getLastShape(impostor.physicsBody);
  86432. impostor.object.position.copyFrom(parentShape.position);
  86433. console.log(parentShape.position);
  86434. } else {*/
  86435. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86436. //}
  86437. if (impostor.object.rotationQuaternion) {
  86438. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86439. }
  86440. }
  86441. };
  86442. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86443. var body = impostor.physicsBody;
  86444. body.position.copy(newPosition);
  86445. body.orientation.copy(newRotation);
  86446. body.syncShapes();
  86447. body.awake();
  86448. };
  86449. /*private _getLastShape(body: any): any {
  86450. var lastShape = body.shapes;
  86451. while (lastShape.next) {
  86452. lastShape = lastShape.next;
  86453. }
  86454. return lastShape;
  86455. }*/
  86456. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86457. impostor.physicsBody.linearVelocity.copy(velocity);
  86458. };
  86459. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86460. impostor.physicsBody.angularVelocity.copy(velocity);
  86461. };
  86462. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86463. var v = impostor.physicsBody.linearVelocity;
  86464. if (!v) {
  86465. return null;
  86466. }
  86467. return new BABYLON.Vector3(v.x, v.y, v.z);
  86468. };
  86469. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86470. var v = impostor.physicsBody.angularVelocity;
  86471. if (!v) {
  86472. return null;
  86473. }
  86474. return new BABYLON.Vector3(v.x, v.y, v.z);
  86475. };
  86476. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86477. var staticBody = mass === 0;
  86478. //this will actually set the body's density and not its mass.
  86479. //But this is how oimo treats the mass variable.
  86480. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86481. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86482. };
  86483. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86484. return impostor.physicsBody.shapes.density;
  86485. };
  86486. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86487. return impostor.physicsBody.shapes.friction;
  86488. };
  86489. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86490. impostor.physicsBody.shapes.friction = friction;
  86491. };
  86492. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86493. return impostor.physicsBody.shapes.restitution;
  86494. };
  86495. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86496. impostor.physicsBody.shapes.restitution = restitution;
  86497. };
  86498. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86499. impostor.physicsBody.sleep();
  86500. };
  86501. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86502. impostor.physicsBody.awake();
  86503. };
  86504. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86505. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86506. if (minDistance !== void 0) {
  86507. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86508. }
  86509. };
  86510. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86511. //TODO separate rotational and transational motors.
  86512. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86513. if (motor) {
  86514. motor.setMotor(speed, maxForce);
  86515. }
  86516. };
  86517. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86518. //TODO separate rotational and transational motors.
  86519. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86520. if (motor) {
  86521. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86522. }
  86523. };
  86524. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86525. var body = impostor.physicsBody;
  86526. mesh.position.x = body.position.x;
  86527. mesh.position.y = body.position.y;
  86528. mesh.position.z = body.position.z;
  86529. if (mesh.rotationQuaternion) {
  86530. mesh.rotationQuaternion.x = body.orientation.x;
  86531. mesh.rotationQuaternion.y = body.orientation.y;
  86532. mesh.rotationQuaternion.z = body.orientation.z;
  86533. mesh.rotationQuaternion.w = body.orientation.s;
  86534. }
  86535. };
  86536. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86537. return impostor.physicsBody.shapes.radius;
  86538. };
  86539. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86540. var shape = impostor.physicsBody.shapes;
  86541. result.x = shape.halfWidth * 2;
  86542. result.y = shape.halfHeight * 2;
  86543. result.z = shape.halfDepth * 2;
  86544. };
  86545. OimoJSPlugin.prototype.dispose = function () {
  86546. this.world.clear();
  86547. };
  86548. return OimoJSPlugin;
  86549. }());
  86550. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86551. })(BABYLON || (BABYLON = {}));
  86552. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86553. var BABYLON;
  86554. (function (BABYLON) {
  86555. /*
  86556. * Based on jsTGALoader - Javascript loader for TGA file
  86557. * By Vincent Thibault
  86558. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86559. */
  86560. var TGATools = /** @class */ (function () {
  86561. function TGATools() {
  86562. }
  86563. TGATools.GetTGAHeader = function (data) {
  86564. var offset = 0;
  86565. var header = {
  86566. id_length: data[offset++],
  86567. colormap_type: data[offset++],
  86568. image_type: data[offset++],
  86569. colormap_index: data[offset++] | data[offset++] << 8,
  86570. colormap_length: data[offset++] | data[offset++] << 8,
  86571. colormap_size: data[offset++],
  86572. origin: [
  86573. data[offset++] | data[offset++] << 8,
  86574. data[offset++] | data[offset++] << 8
  86575. ],
  86576. width: data[offset++] | data[offset++] << 8,
  86577. height: data[offset++] | data[offset++] << 8,
  86578. pixel_size: data[offset++],
  86579. flags: data[offset++]
  86580. };
  86581. return header;
  86582. };
  86583. TGATools.UploadContent = function (gl, data) {
  86584. // Not enough data to contain header ?
  86585. if (data.length < 19) {
  86586. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86587. return;
  86588. }
  86589. // Read Header
  86590. var offset = 18;
  86591. var header = TGATools.GetTGAHeader(data);
  86592. // Assume it's a valid Targa file.
  86593. if (header.id_length + offset > data.length) {
  86594. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86595. return;
  86596. }
  86597. // Skip not needed data
  86598. offset += header.id_length;
  86599. var use_rle = false;
  86600. var use_pal = false;
  86601. var use_grey = false;
  86602. // Get some informations.
  86603. switch (header.image_type) {
  86604. case TGATools._TYPE_RLE_INDEXED:
  86605. use_rle = true;
  86606. case TGATools._TYPE_INDEXED:
  86607. use_pal = true;
  86608. break;
  86609. case TGATools._TYPE_RLE_RGB:
  86610. use_rle = true;
  86611. case TGATools._TYPE_RGB:
  86612. // use_rgb = true;
  86613. break;
  86614. case TGATools._TYPE_RLE_GREY:
  86615. use_rle = true;
  86616. case TGATools._TYPE_GREY:
  86617. use_grey = true;
  86618. break;
  86619. }
  86620. var pixel_data;
  86621. // var numAlphaBits = header.flags & 0xf;
  86622. var pixel_size = header.pixel_size >> 3;
  86623. var pixel_total = header.width * header.height * pixel_size;
  86624. // Read palettes
  86625. var palettes;
  86626. if (use_pal) {
  86627. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86628. }
  86629. // Read LRE
  86630. if (use_rle) {
  86631. pixel_data = new Uint8Array(pixel_total);
  86632. var c, count, i;
  86633. var localOffset = 0;
  86634. var pixels = new Uint8Array(pixel_size);
  86635. while (offset < pixel_total && localOffset < pixel_total) {
  86636. c = data[offset++];
  86637. count = (c & 0x7f) + 1;
  86638. // RLE pixels
  86639. if (c & 0x80) {
  86640. // Bind pixel tmp array
  86641. for (i = 0; i < pixel_size; ++i) {
  86642. pixels[i] = data[offset++];
  86643. }
  86644. // Copy pixel array
  86645. for (i = 0; i < count; ++i) {
  86646. pixel_data.set(pixels, localOffset + i * pixel_size);
  86647. }
  86648. localOffset += pixel_size * count;
  86649. }
  86650. // Raw pixels
  86651. else {
  86652. count *= pixel_size;
  86653. for (i = 0; i < count; ++i) {
  86654. pixel_data[localOffset + i] = data[offset++];
  86655. }
  86656. localOffset += count;
  86657. }
  86658. }
  86659. }
  86660. // RAW Pixels
  86661. else {
  86662. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86663. }
  86664. // Load to texture
  86665. var x_start, y_start, x_step, y_step, y_end, x_end;
  86666. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86667. default:
  86668. case TGATools._ORIGIN_UL:
  86669. x_start = 0;
  86670. x_step = 1;
  86671. x_end = header.width;
  86672. y_start = 0;
  86673. y_step = 1;
  86674. y_end = header.height;
  86675. break;
  86676. case TGATools._ORIGIN_BL:
  86677. x_start = 0;
  86678. x_step = 1;
  86679. x_end = header.width;
  86680. y_start = header.height - 1;
  86681. y_step = -1;
  86682. y_end = -1;
  86683. break;
  86684. case TGATools._ORIGIN_UR:
  86685. x_start = header.width - 1;
  86686. x_step = -1;
  86687. x_end = -1;
  86688. y_start = 0;
  86689. y_step = 1;
  86690. y_end = header.height;
  86691. break;
  86692. case TGATools._ORIGIN_BR:
  86693. x_start = header.width - 1;
  86694. x_step = -1;
  86695. x_end = -1;
  86696. y_start = header.height - 1;
  86697. y_step = -1;
  86698. y_end = -1;
  86699. break;
  86700. }
  86701. // Load the specify method
  86702. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86703. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86704. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86705. };
  86706. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86707. var image = pixel_data, colormap = palettes;
  86708. var width = header.width, height = header.height;
  86709. var color, i = 0, x, y;
  86710. var imageData = new Uint8Array(width * height * 4);
  86711. for (y = y_start; y !== y_end; y += y_step) {
  86712. for (x = x_start; x !== x_end; x += x_step, i++) {
  86713. color = image[i];
  86714. imageData[(x + width * y) * 4 + 3] = 255;
  86715. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86716. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86717. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86718. }
  86719. }
  86720. return imageData;
  86721. };
  86722. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86723. var image = pixel_data;
  86724. var width = header.width, height = header.height;
  86725. var color, i = 0, x, y;
  86726. var imageData = new Uint8Array(width * height * 4);
  86727. for (y = y_start; y !== y_end; y += y_step) {
  86728. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86729. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86730. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86731. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86732. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86733. imageData[(x + width * y) * 4 + 0] = r;
  86734. imageData[(x + width * y) * 4 + 1] = g;
  86735. imageData[(x + width * y) * 4 + 2] = b;
  86736. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86737. }
  86738. }
  86739. return imageData;
  86740. };
  86741. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86742. var image = pixel_data;
  86743. var width = header.width, height = header.height;
  86744. var i = 0, x, y;
  86745. var imageData = new Uint8Array(width * height * 4);
  86746. for (y = y_start; y !== y_end; y += y_step) {
  86747. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86748. imageData[(x + width * y) * 4 + 3] = 255;
  86749. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86750. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86751. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86752. }
  86753. }
  86754. return imageData;
  86755. };
  86756. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86757. var image = pixel_data;
  86758. var width = header.width, height = header.height;
  86759. var i = 0, x, y;
  86760. var imageData = new Uint8Array(width * height * 4);
  86761. for (y = y_start; y !== y_end; y += y_step) {
  86762. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86763. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86764. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86765. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86766. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86767. }
  86768. }
  86769. return imageData;
  86770. };
  86771. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86772. var image = pixel_data;
  86773. var width = header.width, height = header.height;
  86774. var color, i = 0, x, y;
  86775. var imageData = new Uint8Array(width * height * 4);
  86776. for (y = y_start; y !== y_end; y += y_step) {
  86777. for (x = x_start; x !== x_end; x += x_step, i++) {
  86778. color = image[i];
  86779. imageData[(x + width * y) * 4 + 0] = color;
  86780. imageData[(x + width * y) * 4 + 1] = color;
  86781. imageData[(x + width * y) * 4 + 2] = color;
  86782. imageData[(x + width * y) * 4 + 3] = 255;
  86783. }
  86784. }
  86785. return imageData;
  86786. };
  86787. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86788. var image = pixel_data;
  86789. var width = header.width, height = header.height;
  86790. var i = 0, x, y;
  86791. var imageData = new Uint8Array(width * height * 4);
  86792. for (y = y_start; y !== y_end; y += y_step) {
  86793. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86794. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  86795. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  86796. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86797. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86798. }
  86799. }
  86800. return imageData;
  86801. };
  86802. //private static _TYPE_NO_DATA = 0;
  86803. TGATools._TYPE_INDEXED = 1;
  86804. TGATools._TYPE_RGB = 2;
  86805. TGATools._TYPE_GREY = 3;
  86806. TGATools._TYPE_RLE_INDEXED = 9;
  86807. TGATools._TYPE_RLE_RGB = 10;
  86808. TGATools._TYPE_RLE_GREY = 11;
  86809. TGATools._ORIGIN_MASK = 0x30;
  86810. TGATools._ORIGIN_SHIFT = 0x04;
  86811. TGATools._ORIGIN_BL = 0x00;
  86812. TGATools._ORIGIN_BR = 0x01;
  86813. TGATools._ORIGIN_UL = 0x02;
  86814. TGATools._ORIGIN_UR = 0x03;
  86815. return TGATools;
  86816. }());
  86817. BABYLON.TGATools = TGATools;
  86818. })(BABYLON || (BABYLON = {}));
  86819. //# sourceMappingURL=babylon.tga.js.map
  86820. var BABYLON;
  86821. (function (BABYLON) {
  86822. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86823. // All values and structures referenced from:
  86824. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86825. var DDS_MAGIC = 0x20534444;
  86826. var
  86827. //DDSD_CAPS = 0x1,
  86828. //DDSD_HEIGHT = 0x2,
  86829. //DDSD_WIDTH = 0x4,
  86830. //DDSD_PITCH = 0x8,
  86831. //DDSD_PIXELFORMAT = 0x1000,
  86832. DDSD_MIPMAPCOUNT = 0x20000;
  86833. //DDSD_LINEARSIZE = 0x80000,
  86834. //DDSD_DEPTH = 0x800000;
  86835. // var DDSCAPS_COMPLEX = 0x8,
  86836. // DDSCAPS_MIPMAP = 0x400000,
  86837. // DDSCAPS_TEXTURE = 0x1000;
  86838. var DDSCAPS2_CUBEMAP = 0x200;
  86839. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86840. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86841. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86842. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86843. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86844. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86845. // DDSCAPS2_VOLUME = 0x200000;
  86846. var
  86847. //DDPF_ALPHAPIXELS = 0x1,
  86848. //DDPF_ALPHA = 0x2,
  86849. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86850. //DDPF_YUV = 0x200,
  86851. DDPF_LUMINANCE = 0x20000;
  86852. function FourCCToInt32(value) {
  86853. return value.charCodeAt(0) +
  86854. (value.charCodeAt(1) << 8) +
  86855. (value.charCodeAt(2) << 16) +
  86856. (value.charCodeAt(3) << 24);
  86857. }
  86858. function Int32ToFourCC(value) {
  86859. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  86860. }
  86861. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  86862. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  86863. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  86864. var FOURCC_DX10 = FourCCToInt32("DX10");
  86865. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  86866. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  86867. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  86868. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  86869. var headerLengthInt = 31; // The header length in 32 bit ints
  86870. // Offsets into the header array
  86871. var off_magic = 0;
  86872. var off_size = 1;
  86873. var off_flags = 2;
  86874. var off_height = 3;
  86875. var off_width = 4;
  86876. var off_mipmapCount = 7;
  86877. var off_pfFlags = 20;
  86878. var off_pfFourCC = 21;
  86879. var off_RGBbpp = 22;
  86880. var off_RMask = 23;
  86881. var off_GMask = 24;
  86882. var off_BMask = 25;
  86883. var off_AMask = 26;
  86884. // var off_caps1 = 27;
  86885. var off_caps2 = 28;
  86886. // var off_caps3 = 29;
  86887. // var off_caps4 = 30;
  86888. var off_dxgiFormat = 32;
  86889. ;
  86890. var DDSTools = /** @class */ (function () {
  86891. function DDSTools() {
  86892. }
  86893. DDSTools.GetDDSInfo = function (arrayBuffer) {
  86894. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86895. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  86896. var mipmapCount = 1;
  86897. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  86898. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86899. }
  86900. var fourCC = header[off_pfFourCC];
  86901. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  86902. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86903. switch (fourCC) {
  86904. case FOURCC_D3DFMT_R16G16B16A16F:
  86905. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86906. break;
  86907. case FOURCC_D3DFMT_R32G32B32A32F:
  86908. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86909. break;
  86910. case FOURCC_DX10:
  86911. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  86912. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86913. break;
  86914. }
  86915. }
  86916. return {
  86917. width: header[off_width],
  86918. height: header[off_height],
  86919. mipmapCount: mipmapCount,
  86920. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  86921. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  86922. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  86923. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  86924. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  86925. dxgiFormat: dxgiFormat,
  86926. textureType: textureType
  86927. };
  86928. };
  86929. DDSTools._ToHalfFloat = function (value) {
  86930. if (!DDSTools._FloatView) {
  86931. DDSTools._FloatView = new Float32Array(1);
  86932. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  86933. }
  86934. DDSTools._FloatView[0] = value;
  86935. var x = DDSTools._Int32View[0];
  86936. var bits = (x >> 16) & 0x8000; /* Get the sign */
  86937. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  86938. var e = (x >> 23) & 0xff; /* Using int is faster here */
  86939. /* If zero, or denormal, or exponent underflows too much for a denormal
  86940. * half, return signed zero. */
  86941. if (e < 103) {
  86942. return bits;
  86943. }
  86944. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  86945. if (e > 142) {
  86946. bits |= 0x7c00;
  86947. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  86948. * not Inf, so make sure we set one mantissa bit too. */
  86949. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  86950. return bits;
  86951. }
  86952. /* If exponent underflows but not too much, return a denormal */
  86953. if (e < 113) {
  86954. m |= 0x0800;
  86955. /* Extra rounding may overflow and set mantissa to 0 and exponent
  86956. * to 1, which is OK. */
  86957. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  86958. return bits;
  86959. }
  86960. bits |= ((e - 112) << 10) | (m >> 1);
  86961. bits += m & 1;
  86962. return bits;
  86963. };
  86964. DDSTools._FromHalfFloat = function (value) {
  86965. var s = (value & 0x8000) >> 15;
  86966. var e = (value & 0x7C00) >> 10;
  86967. var f = value & 0x03FF;
  86968. if (e === 0) {
  86969. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  86970. }
  86971. else if (e == 0x1F) {
  86972. return f ? NaN : ((s ? -1 : 1) * Infinity);
  86973. }
  86974. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  86975. };
  86976. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86977. var destArray = new Float32Array(dataLength);
  86978. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86979. var index = 0;
  86980. for (var y = 0; y < height; y++) {
  86981. for (var x = 0; x < width; x++) {
  86982. var srcPos = (x + y * width) * 4;
  86983. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  86984. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  86985. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  86986. if (DDSTools.StoreLODInAlphaChannel) {
  86987. destArray[index + 3] = lod;
  86988. }
  86989. else {
  86990. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  86991. }
  86992. index += 4;
  86993. }
  86994. }
  86995. return destArray;
  86996. };
  86997. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86998. if (DDSTools.StoreLODInAlphaChannel) {
  86999. var destArray = new Uint16Array(dataLength);
  87000. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87001. var index = 0;
  87002. for (var y = 0; y < height; y++) {
  87003. for (var x = 0; x < width; x++) {
  87004. var srcPos = (x + y * width) * 4;
  87005. destArray[index] = srcData[srcPos];
  87006. destArray[index + 1] = srcData[srcPos + 1];
  87007. destArray[index + 2] = srcData[srcPos + 2];
  87008. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87009. index += 4;
  87010. }
  87011. }
  87012. return destArray;
  87013. }
  87014. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87015. };
  87016. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87017. if (DDSTools.StoreLODInAlphaChannel) {
  87018. var destArray = new Float32Array(dataLength);
  87019. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87020. var index = 0;
  87021. for (var y = 0; y < height; y++) {
  87022. for (var x = 0; x < width; x++) {
  87023. var srcPos = (x + y * width) * 4;
  87024. destArray[index] = srcData[srcPos];
  87025. destArray[index + 1] = srcData[srcPos + 1];
  87026. destArray[index + 2] = srcData[srcPos + 2];
  87027. destArray[index + 3] = lod;
  87028. index += 4;
  87029. }
  87030. }
  87031. return destArray;
  87032. }
  87033. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87034. };
  87035. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87036. var destArray = new Uint8Array(dataLength);
  87037. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87038. var index = 0;
  87039. for (var y = 0; y < height; y++) {
  87040. for (var x = 0; x < width; x++) {
  87041. var srcPos = (x + y * width) * 4;
  87042. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87043. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87044. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87045. if (DDSTools.StoreLODInAlphaChannel) {
  87046. destArray[index + 3] = lod;
  87047. }
  87048. else {
  87049. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87050. }
  87051. index += 4;
  87052. }
  87053. }
  87054. return destArray;
  87055. };
  87056. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87057. var destArray = new Uint8Array(dataLength);
  87058. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87059. var index = 0;
  87060. for (var y = 0; y < height; y++) {
  87061. for (var x = 0; x < width; x++) {
  87062. var srcPos = (x + y * width) * 4;
  87063. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87064. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87065. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87066. if (DDSTools.StoreLODInAlphaChannel) {
  87067. destArray[index + 3] = lod;
  87068. }
  87069. else {
  87070. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87071. }
  87072. index += 4;
  87073. }
  87074. }
  87075. return destArray;
  87076. };
  87077. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87078. var byteArray = new Uint8Array(dataLength);
  87079. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87080. var index = 0;
  87081. for (var y = 0; y < height; y++) {
  87082. for (var x = 0; x < width; x++) {
  87083. var srcPos = (x + y * width) * 4;
  87084. byteArray[index] = srcData[srcPos + rOffset];
  87085. byteArray[index + 1] = srcData[srcPos + gOffset];
  87086. byteArray[index + 2] = srcData[srcPos + bOffset];
  87087. byteArray[index + 3] = srcData[srcPos + aOffset];
  87088. index += 4;
  87089. }
  87090. }
  87091. return byteArray;
  87092. };
  87093. DDSTools._ExtractLongWordOrder = function (value) {
  87094. if (value === 0 || value === 255 || value === -16777216) {
  87095. return 0;
  87096. }
  87097. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87098. };
  87099. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87100. var byteArray = new Uint8Array(dataLength);
  87101. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87102. var index = 0;
  87103. for (var y = 0; y < height; y++) {
  87104. for (var x = 0; x < width; x++) {
  87105. var srcPos = (x + y * width) * 3;
  87106. byteArray[index] = srcData[srcPos + rOffset];
  87107. byteArray[index + 1] = srcData[srcPos + gOffset];
  87108. byteArray[index + 2] = srcData[srcPos + bOffset];
  87109. index += 3;
  87110. }
  87111. }
  87112. return byteArray;
  87113. };
  87114. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87115. var byteArray = new Uint8Array(dataLength);
  87116. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87117. var index = 0;
  87118. for (var y = 0; y < height; y++) {
  87119. for (var x = 0; x < width; x++) {
  87120. var srcPos = (x + y * width);
  87121. byteArray[index] = srcData[srcPos];
  87122. index++;
  87123. }
  87124. }
  87125. return byteArray;
  87126. };
  87127. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87128. if (lodIndex === void 0) { lodIndex = -1; }
  87129. var sphericalPolynomialFaces = null;
  87130. if (info.sphericalPolynomial) {
  87131. sphericalPolynomialFaces = new Array();
  87132. }
  87133. var ext = engine.getCaps().s3tc;
  87134. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87135. var fourCC, width, height, dataLength = 0, dataOffset;
  87136. var byteArray, mipmapCount, mip;
  87137. var internalFormat = 0;
  87138. var format = 0;
  87139. var blockBytes = 1;
  87140. if (header[off_magic] !== DDS_MAGIC) {
  87141. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87142. return;
  87143. }
  87144. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87145. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87146. return;
  87147. }
  87148. if (info.isCompressed && !ext) {
  87149. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87150. return;
  87151. }
  87152. var bpp = header[off_RGBbpp];
  87153. dataOffset = header[off_size] + 4;
  87154. var computeFormats = false;
  87155. if (info.isFourCC) {
  87156. fourCC = header[off_pfFourCC];
  87157. switch (fourCC) {
  87158. case FOURCC_DXT1:
  87159. blockBytes = 8;
  87160. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87161. break;
  87162. case FOURCC_DXT3:
  87163. blockBytes = 16;
  87164. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87165. break;
  87166. case FOURCC_DXT5:
  87167. blockBytes = 16;
  87168. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87169. break;
  87170. case FOURCC_D3DFMT_R16G16B16A16F:
  87171. computeFormats = true;
  87172. break;
  87173. case FOURCC_D3DFMT_R32G32B32A32F:
  87174. computeFormats = true;
  87175. break;
  87176. case FOURCC_DX10:
  87177. // There is an additionnal header so dataOffset need to be changed
  87178. dataOffset += 5 * 4; // 5 uints
  87179. var supported = false;
  87180. switch (info.dxgiFormat) {
  87181. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87182. computeFormats = true;
  87183. supported = true;
  87184. break;
  87185. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87186. info.isRGB = true;
  87187. info.isFourCC = false;
  87188. bpp = 32;
  87189. supported = true;
  87190. break;
  87191. }
  87192. if (supported) {
  87193. break;
  87194. }
  87195. default:
  87196. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87197. return;
  87198. }
  87199. }
  87200. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87201. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87202. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87203. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87204. if (computeFormats) {
  87205. format = engine._getWebGLTextureType(info.textureType);
  87206. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87207. }
  87208. mipmapCount = 1;
  87209. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87210. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87211. }
  87212. for (var face = 0; face < faces; face++) {
  87213. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  87214. width = header[off_width];
  87215. height = header[off_height];
  87216. for (mip = 0; mip < mipmapCount; ++mip) {
  87217. if (lodIndex === -1 || lodIndex === mip) {
  87218. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87219. var i = (lodIndex === -1) ? mip : 0;
  87220. if (!info.isCompressed && info.isFourCC) {
  87221. dataLength = width * height * 4;
  87222. var floatArray = null;
  87223. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87224. if (bpp === 128) {
  87225. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87226. if (sphericalPolynomialFaces && i == 0) {
  87227. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87228. }
  87229. }
  87230. else if (bpp === 64) {
  87231. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87232. if (sphericalPolynomialFaces && i == 0) {
  87233. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87234. }
  87235. }
  87236. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87237. format = engine._getWebGLTextureType(info.textureType);
  87238. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87239. }
  87240. else {
  87241. if (bpp === 128) {
  87242. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87243. if (sphericalPolynomialFaces && i == 0) {
  87244. sphericalPolynomialFaces.push(floatArray);
  87245. }
  87246. }
  87247. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87248. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87249. if (sphericalPolynomialFaces && i == 0) {
  87250. sphericalPolynomialFaces.push(floatArray);
  87251. }
  87252. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87253. format = engine._getWebGLTextureType(info.textureType);
  87254. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87255. }
  87256. else { // 64
  87257. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87258. if (sphericalPolynomialFaces && i == 0) {
  87259. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87260. }
  87261. }
  87262. }
  87263. if (floatArray) {
  87264. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  87265. }
  87266. }
  87267. else if (info.isRGB) {
  87268. if (bpp === 24) {
  87269. dataLength = width * height * 3;
  87270. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87271. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  87272. }
  87273. else { // 32
  87274. dataLength = width * height * 4;
  87275. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87276. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  87277. }
  87278. }
  87279. else if (info.isLuminance) {
  87280. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  87281. var unpaddedRowSize = width;
  87282. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87283. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87284. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87285. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  87286. }
  87287. else {
  87288. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87289. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87290. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  87291. }
  87292. }
  87293. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87294. width *= 0.5;
  87295. height *= 0.5;
  87296. width = Math.max(1.0, width);
  87297. height = Math.max(1.0, height);
  87298. }
  87299. if (currentFace !== undefined) {
  87300. // Loading a single face
  87301. break;
  87302. }
  87303. }
  87304. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87305. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87306. size: header[off_width],
  87307. right: sphericalPolynomialFaces[0],
  87308. left: sphericalPolynomialFaces[1],
  87309. up: sphericalPolynomialFaces[2],
  87310. down: sphericalPolynomialFaces[3],
  87311. front: sphericalPolynomialFaces[4],
  87312. back: sphericalPolynomialFaces[5],
  87313. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87314. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87315. gammaSpace: false,
  87316. });
  87317. }
  87318. else {
  87319. info.sphericalPolynomial = undefined;
  87320. }
  87321. };
  87322. DDSTools.StoreLODInAlphaChannel = false;
  87323. return DDSTools;
  87324. }());
  87325. BABYLON.DDSTools = DDSTools;
  87326. })(BABYLON || (BABYLON = {}));
  87327. //# sourceMappingURL=babylon.dds.js.map
  87328. var BABYLON;
  87329. (function (BABYLON) {
  87330. /**
  87331. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87332. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87333. */
  87334. var KhronosTextureContainer = /** @class */ (function () {
  87335. /**
  87336. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87337. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87338. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87339. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87340. */
  87341. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87342. this.arrayBuffer = arrayBuffer;
  87343. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87344. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87345. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87346. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87347. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87348. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87349. BABYLON.Tools.Error("texture missing KTX identifier");
  87350. return;
  87351. }
  87352. // load the reset of the header in native 32 bit int
  87353. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87354. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87355. var oppositeEndianess = header[0] === 0x01020304;
  87356. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87357. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87358. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87359. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87360. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87361. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87362. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87363. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87364. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87365. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87366. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87367. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87368. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87369. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87370. if (this.glType !== 0) {
  87371. BABYLON.Tools.Error("only compressed formats currently supported");
  87372. return;
  87373. }
  87374. else {
  87375. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87376. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87377. }
  87378. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87379. BABYLON.Tools.Error("only 2D textures currently supported");
  87380. return;
  87381. }
  87382. if (this.numberOfArrayElements !== 0) {
  87383. BABYLON.Tools.Error("texture arrays not currently supported");
  87384. return;
  87385. }
  87386. if (this.numberOfFaces !== facesExpected) {
  87387. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87388. return;
  87389. }
  87390. // we now have a completely validated file, so could use existence of loadType as success
  87391. // would need to make this more elaborate & adjust checks above to support more than one load type
  87392. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87393. }
  87394. // not as fast hardware based, but will probably never need to use
  87395. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87396. return ((val & 0xFF) << 24)
  87397. | ((val & 0xFF00) << 8)
  87398. | ((val >> 8) & 0xFF00)
  87399. | ((val >> 24) & 0xFF);
  87400. };
  87401. /**
  87402. * It is assumed that the texture has already been created & is currently bound
  87403. */
  87404. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87405. switch (this.loadType) {
  87406. case KhronosTextureContainer.COMPRESSED_2D:
  87407. this._upload2DCompressedLevels(gl, loadMipmaps);
  87408. break;
  87409. case KhronosTextureContainer.TEX_2D:
  87410. case KhronosTextureContainer.COMPRESSED_3D:
  87411. case KhronosTextureContainer.TEX_3D:
  87412. }
  87413. };
  87414. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87415. // initialize width & height for level 1
  87416. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87417. var width = this.pixelWidth;
  87418. var height = this.pixelHeight;
  87419. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87420. for (var level = 0; level < mipmapCount; level++) {
  87421. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87422. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87423. for (var face = 0; face < this.numberOfFaces; face++) {
  87424. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87425. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87426. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87427. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87428. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87429. }
  87430. width = Math.max(1.0, width * 0.5);
  87431. height = Math.max(1.0, height * 0.5);
  87432. }
  87433. };
  87434. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87435. // load types
  87436. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87437. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87438. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87439. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87440. return KhronosTextureContainer;
  87441. }());
  87442. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87443. })(BABYLON || (BABYLON = {}));
  87444. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87445. var BABYLON;
  87446. (function (BABYLON) {
  87447. var Debug;
  87448. (function (Debug) {
  87449. /**
  87450. * Class used to render a debug view of a given skeleton
  87451. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87452. */
  87453. var SkeletonViewer = /** @class */ (function () {
  87454. /**
  87455. * Creates a new SkeletonViewer
  87456. * @param skeleton defines the skeleton to render
  87457. * @param mesh defines the mesh attached to the skeleton
  87458. * @param scene defines the hosting scene
  87459. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87460. * @param renderingGroupId defines the rendering group id to use with the viewer
  87461. */
  87462. function SkeletonViewer(
  87463. /** defines the skeleton to render */
  87464. skeleton,
  87465. /** defines the mesh attached to the skeleton */
  87466. mesh, scene,
  87467. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87468. autoUpdateBonesMatrices,
  87469. /** defines the rendering group id to use with the viewer */
  87470. renderingGroupId) {
  87471. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87472. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87473. this.skeleton = skeleton;
  87474. this.mesh = mesh;
  87475. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87476. this.renderingGroupId = renderingGroupId;
  87477. /** Gets or sets the color used to render the skeleton */
  87478. this.color = BABYLON.Color3.White();
  87479. this._debugLines = new Array();
  87480. this._isEnabled = false;
  87481. this._scene = scene;
  87482. this.update();
  87483. this._renderFunction = this.update.bind(this);
  87484. }
  87485. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87486. get: function () {
  87487. return this._isEnabled;
  87488. },
  87489. /** Gets or sets a boolean indicating if the viewer is enabled */
  87490. set: function (value) {
  87491. if (this._isEnabled === value) {
  87492. return;
  87493. }
  87494. this._isEnabled = value;
  87495. if (value) {
  87496. this._scene.registerBeforeRender(this._renderFunction);
  87497. }
  87498. else {
  87499. this._scene.unregisterBeforeRender(this._renderFunction);
  87500. }
  87501. },
  87502. enumerable: true,
  87503. configurable: true
  87504. });
  87505. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87506. if (x === void 0) { x = 0; }
  87507. if (y === void 0) { y = 0; }
  87508. if (z === void 0) { z = 0; }
  87509. var tmat = BABYLON.Tmp.Matrix[0];
  87510. var parentBone = bone.getParent();
  87511. tmat.copyFrom(bone.getLocalMatrix());
  87512. if (x !== 0 || y !== 0 || z !== 0) {
  87513. var tmat2 = BABYLON.Tmp.Matrix[1];
  87514. BABYLON.Matrix.IdentityToRef(tmat2);
  87515. tmat2.m[12] = x;
  87516. tmat2.m[13] = y;
  87517. tmat2.m[14] = z;
  87518. tmat2.multiplyToRef(tmat, tmat);
  87519. }
  87520. if (parentBone) {
  87521. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87522. }
  87523. tmat.multiplyToRef(meshMat, tmat);
  87524. position.x = tmat.m[12];
  87525. position.y = tmat.m[13];
  87526. position.z = tmat.m[14];
  87527. };
  87528. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87529. var len = bones.length;
  87530. var meshPos = this.mesh.position;
  87531. for (var i = 0; i < len; i++) {
  87532. var bone = bones[i];
  87533. var points = this._debugLines[i];
  87534. if (!points) {
  87535. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87536. this._debugLines[i] = points;
  87537. }
  87538. this._getBonePosition(points[0], bone, meshMat);
  87539. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87540. points[0].subtractInPlace(meshPos);
  87541. points[1].subtractInPlace(meshPos);
  87542. }
  87543. };
  87544. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87545. var len = bones.length;
  87546. var boneNum = 0;
  87547. var meshPos = this.mesh.position;
  87548. for (var i = len - 1; i >= 0; i--) {
  87549. var childBone = bones[i];
  87550. var parentBone = childBone.getParent();
  87551. if (!parentBone) {
  87552. continue;
  87553. }
  87554. var points = this._debugLines[boneNum];
  87555. if (!points) {
  87556. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87557. this._debugLines[boneNum] = points;
  87558. }
  87559. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87560. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87561. points[0].subtractInPlace(meshPos);
  87562. points[1].subtractInPlace(meshPos);
  87563. boneNum++;
  87564. }
  87565. };
  87566. /** Update the viewer to sync with current skeleton state */
  87567. SkeletonViewer.prototype.update = function () {
  87568. if (this.autoUpdateBonesMatrices) {
  87569. this.skeleton.computeAbsoluteTransforms();
  87570. }
  87571. if (this.skeleton.bones[0].length === undefined) {
  87572. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87573. }
  87574. else {
  87575. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87576. }
  87577. if (!this._debugMesh) {
  87578. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87579. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87580. }
  87581. else {
  87582. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87583. }
  87584. this._debugMesh.position.copyFrom(this.mesh.position);
  87585. this._debugMesh.color = this.color;
  87586. };
  87587. /** Release associated resources */
  87588. SkeletonViewer.prototype.dispose = function () {
  87589. if (this._debugMesh) {
  87590. this.isEnabled = false;
  87591. this._debugMesh.dispose();
  87592. this._debugMesh = null;
  87593. }
  87594. };
  87595. return SkeletonViewer;
  87596. }());
  87597. Debug.SkeletonViewer = SkeletonViewer;
  87598. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87599. })(BABYLON || (BABYLON = {}));
  87600. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87601. /**
  87602. * Module Debug contains the (visual) components to debug a scene correctly
  87603. */
  87604. var BABYLON;
  87605. (function (BABYLON) {
  87606. var Debug;
  87607. (function (Debug) {
  87608. /**
  87609. * The Axes viewer will show 3 axes in a specific point in space
  87610. */
  87611. var AxesViewer = /** @class */ (function () {
  87612. /**
  87613. * Creates a new AxesViewer
  87614. * @param scene defines the hosting scene
  87615. * @param scaleLines defines a number used to scale line length (1 by default)
  87616. */
  87617. function AxesViewer(scene, scaleLines) {
  87618. if (scaleLines === void 0) { scaleLines = 1; }
  87619. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87620. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87621. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87622. /**
  87623. * Gets or sets a number used to scale line length
  87624. */
  87625. this.scaleLines = 1;
  87626. this.scaleLines = scaleLines;
  87627. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87628. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87629. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87630. this._xmesh.renderingGroupId = 2;
  87631. this._ymesh.renderingGroupId = 2;
  87632. this._zmesh.renderingGroupId = 2;
  87633. this._xmesh.material.checkReadyOnlyOnce = true;
  87634. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87635. this._ymesh.material.checkReadyOnlyOnce = true;
  87636. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87637. this._zmesh.material.checkReadyOnlyOnce = true;
  87638. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87639. this.scene = scene;
  87640. }
  87641. /**
  87642. * Force the viewer to update
  87643. * @param position defines the position of the viewer
  87644. * @param xaxis defines the x axis of the viewer
  87645. * @param yaxis defines the y axis of the viewer
  87646. * @param zaxis defines the z axis of the viewer
  87647. */
  87648. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87649. var scaleLines = this.scaleLines;
  87650. if (this._xmesh) {
  87651. this._xmesh.position.copyFrom(position);
  87652. }
  87653. if (this._ymesh) {
  87654. this._ymesh.position.copyFrom(position);
  87655. }
  87656. if (this._zmesh) {
  87657. this._zmesh.position.copyFrom(position);
  87658. }
  87659. var point2 = this._xline[1];
  87660. point2.x = xaxis.x * scaleLines;
  87661. point2.y = xaxis.y * scaleLines;
  87662. point2.z = xaxis.z * scaleLines;
  87663. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87664. point2 = this._yline[1];
  87665. point2.x = yaxis.x * scaleLines;
  87666. point2.y = yaxis.y * scaleLines;
  87667. point2.z = yaxis.z * scaleLines;
  87668. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87669. point2 = this._zline[1];
  87670. point2.x = zaxis.x * scaleLines;
  87671. point2.y = zaxis.y * scaleLines;
  87672. point2.z = zaxis.z * scaleLines;
  87673. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87674. };
  87675. /** Releases resources */
  87676. AxesViewer.prototype.dispose = function () {
  87677. if (this._xmesh) {
  87678. this._xmesh.dispose();
  87679. }
  87680. if (this._ymesh) {
  87681. this._ymesh.dispose();
  87682. }
  87683. if (this._zmesh) {
  87684. this._zmesh.dispose();
  87685. }
  87686. this._xmesh = null;
  87687. this._ymesh = null;
  87688. this._zmesh = null;
  87689. this.scene = null;
  87690. };
  87691. return AxesViewer;
  87692. }());
  87693. Debug.AxesViewer = AxesViewer;
  87694. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87695. })(BABYLON || (BABYLON = {}));
  87696. //# sourceMappingURL=babylon.axesViewer.js.map
  87697. var BABYLON;
  87698. (function (BABYLON) {
  87699. var Debug;
  87700. (function (Debug) {
  87701. /**
  87702. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87703. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87704. */
  87705. var BoneAxesViewer = /** @class */ (function (_super) {
  87706. __extends(BoneAxesViewer, _super);
  87707. /**
  87708. * Creates a new BoneAxesViewer
  87709. * @param scene defines the hosting scene
  87710. * @param bone defines the target bone
  87711. * @param mesh defines the target mesh
  87712. * @param scaleLines defines a scaling factor for line length (1 by default)
  87713. */
  87714. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87715. if (scaleLines === void 0) { scaleLines = 1; }
  87716. var _this = _super.call(this, scene, scaleLines) || this;
  87717. /** Gets current position */
  87718. _this.pos = BABYLON.Vector3.Zero();
  87719. /** Gets direction of X axis */
  87720. _this.xaxis = BABYLON.Vector3.Zero();
  87721. /** Gets direction of Y axis */
  87722. _this.yaxis = BABYLON.Vector3.Zero();
  87723. /** Gets direction of Z axis */
  87724. _this.zaxis = BABYLON.Vector3.Zero();
  87725. _this.mesh = mesh;
  87726. _this.bone = bone;
  87727. return _this;
  87728. }
  87729. /**
  87730. * Force the viewer to update
  87731. */
  87732. BoneAxesViewer.prototype.update = function () {
  87733. if (!this.mesh || !this.bone) {
  87734. return;
  87735. }
  87736. var bone = this.bone;
  87737. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87738. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87739. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87740. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87741. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87742. };
  87743. /** Releases resources */
  87744. BoneAxesViewer.prototype.dispose = function () {
  87745. if (this.mesh) {
  87746. this.mesh = null;
  87747. this.bone = null;
  87748. _super.prototype.dispose.call(this);
  87749. }
  87750. };
  87751. return BoneAxesViewer;
  87752. }(Debug.AxesViewer));
  87753. Debug.BoneAxesViewer = BoneAxesViewer;
  87754. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87755. })(BABYLON || (BABYLON = {}));
  87756. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87757. var BABYLON;
  87758. (function (BABYLON) {
  87759. var RayHelper = /** @class */ (function () {
  87760. function RayHelper(ray) {
  87761. this.ray = ray;
  87762. }
  87763. RayHelper.CreateAndShow = function (ray, scene, color) {
  87764. var helper = new RayHelper(ray);
  87765. helper.show(scene, color);
  87766. return helper;
  87767. };
  87768. RayHelper.prototype.show = function (scene, color) {
  87769. if (!this._renderFunction && this.ray) {
  87770. var ray = this.ray;
  87771. this._renderFunction = this._render.bind(this);
  87772. this._scene = scene;
  87773. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87774. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87775. if (this._renderFunction) {
  87776. this._scene.registerBeforeRender(this._renderFunction);
  87777. }
  87778. }
  87779. if (color && this._renderLine) {
  87780. this._renderLine.color.copyFrom(color);
  87781. }
  87782. };
  87783. RayHelper.prototype.hide = function () {
  87784. if (this._renderFunction && this._scene) {
  87785. this._scene.unregisterBeforeRender(this._renderFunction);
  87786. this._scene = null;
  87787. this._renderFunction = null;
  87788. if (this._renderLine) {
  87789. this._renderLine.dispose();
  87790. this._renderLine = null;
  87791. }
  87792. this._renderPoints = [];
  87793. }
  87794. };
  87795. RayHelper.prototype._render = function () {
  87796. var ray = this.ray;
  87797. if (!ray) {
  87798. return;
  87799. }
  87800. var point = this._renderPoints[1];
  87801. var len = Math.min(ray.length, 1000000);
  87802. point.copyFrom(ray.direction);
  87803. point.scaleInPlace(len);
  87804. point.addInPlace(ray.origin);
  87805. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87806. };
  87807. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87808. this._attachedToMesh = mesh;
  87809. var ray = this.ray;
  87810. if (!ray) {
  87811. return;
  87812. }
  87813. if (!ray.direction) {
  87814. ray.direction = BABYLON.Vector3.Zero();
  87815. }
  87816. if (!ray.origin) {
  87817. ray.origin = BABYLON.Vector3.Zero();
  87818. }
  87819. if (length) {
  87820. ray.length = length;
  87821. }
  87822. if (!meshSpaceOrigin) {
  87823. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87824. }
  87825. if (!meshSpaceDirection) {
  87826. // -1 so that this will work with Mesh.lookAt
  87827. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87828. }
  87829. if (!this._meshSpaceDirection) {
  87830. this._meshSpaceDirection = meshSpaceDirection.clone();
  87831. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87832. }
  87833. else {
  87834. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87835. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87836. }
  87837. if (!this._updateToMeshFunction) {
  87838. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87839. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87840. }
  87841. this._updateToMesh();
  87842. };
  87843. RayHelper.prototype.detachFromMesh = function () {
  87844. if (this._attachedToMesh) {
  87845. if (this._updateToMeshFunction) {
  87846. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87847. }
  87848. this._attachedToMesh = null;
  87849. this._updateToMeshFunction = null;
  87850. }
  87851. };
  87852. RayHelper.prototype._updateToMesh = function () {
  87853. var ray = this.ray;
  87854. if (!this._attachedToMesh || !ray) {
  87855. return;
  87856. }
  87857. if (this._attachedToMesh._isDisposed) {
  87858. this.detachFromMesh();
  87859. return;
  87860. }
  87861. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  87862. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  87863. };
  87864. RayHelper.prototype.dispose = function () {
  87865. this.hide();
  87866. this.detachFromMesh();
  87867. this.ray = null;
  87868. };
  87869. return RayHelper;
  87870. }());
  87871. BABYLON.RayHelper = RayHelper;
  87872. })(BABYLON || (BABYLON = {}));
  87873. //# sourceMappingURL=babylon.rayHelper.js.map
  87874. var BABYLON;
  87875. (function (BABYLON) {
  87876. // load the inspector using require, if not present in the global namespace.
  87877. var DebugLayer = /** @class */ (function () {
  87878. function DebugLayer(scene) {
  87879. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87880. this._scene = scene;
  87881. // load inspector using require, if it doesn't exist on the global namespace.
  87882. }
  87883. /** Creates the inspector window. */
  87884. DebugLayer.prototype._createInspector = function (config) {
  87885. if (config === void 0) { config = {}; }
  87886. var popup = config.popup || false;
  87887. var initialTab = config.initialTab || 0;
  87888. var parentElement = config.parentElement || null;
  87889. if (!this._inspector) {
  87890. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87891. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  87892. } // else nothing to do,; instance is already existing
  87893. };
  87894. DebugLayer.prototype.isVisible = function () {
  87895. if (!this._inspector) {
  87896. return false;
  87897. }
  87898. return true;
  87899. };
  87900. DebugLayer.prototype.hide = function () {
  87901. if (this._inspector) {
  87902. try {
  87903. this._inspector.dispose();
  87904. }
  87905. catch (e) {
  87906. // If the inspector has been removed directly from the inspector tool
  87907. }
  87908. this.onPropertyChangedObservable.clear();
  87909. this._inspector = null;
  87910. }
  87911. };
  87912. /**
  87913. *
  87914. * Launch the debugLayer.
  87915. *
  87916. * initialTab:
  87917. * | Value | Tab Name |
  87918. * | --- | --- |
  87919. * | 0 | Scene |
  87920. * | 1 | Console |
  87921. * | 2 | Stats |
  87922. * | 3 | Textures |
  87923. * | 4 | Mesh |
  87924. * | 5 | Light |
  87925. * | 6 | Material |
  87926. * | 7 | GLTF |
  87927. * | 8 | GUI |
  87928. * | 9 | Physics |
  87929. * | 10 | Camera |
  87930. * | 11 | Audio |
  87931. *
  87932. */
  87933. DebugLayer.prototype.show = function (config) {
  87934. if (config === void 0) { config = {}; }
  87935. if (typeof this.BJSINSPECTOR == 'undefined') {
  87936. // Load inspector and add it to the DOM
  87937. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  87938. }
  87939. else {
  87940. // Otherwise creates the inspector
  87941. this._createInspector(config);
  87942. this.onPropertyChangedObservable = new BABYLON.Observable();
  87943. }
  87944. };
  87945. /**
  87946. * Gets the active tab
  87947. * @return the index of the active tab or -1 if the inspector is hidden
  87948. */
  87949. DebugLayer.prototype.getActiveTab = function () {
  87950. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  87951. };
  87952. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  87953. return DebugLayer;
  87954. }());
  87955. BABYLON.DebugLayer = DebugLayer;
  87956. })(BABYLON || (BABYLON = {}));
  87957. //# sourceMappingURL=babylon.debugLayer.js.map
  87958. var BABYLON;
  87959. (function (BABYLON) {
  87960. var Debug;
  87961. (function (Debug) {
  87962. /**
  87963. * Used to show the physics impostor around the specific mesh
  87964. */
  87965. var PhysicsViewer = /** @class */ (function () {
  87966. /**
  87967. * Creates a new PhysicsViewer
  87968. * @param scene defines the hosting scene
  87969. */
  87970. function PhysicsViewer(scene) {
  87971. /** @hidden */
  87972. this._impostors = [];
  87973. /** @hidden */
  87974. this._meshes = [];
  87975. /** @hidden */
  87976. this._numMeshes = 0;
  87977. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87978. var physicEngine = this._scene.getPhysicsEngine();
  87979. if (physicEngine) {
  87980. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  87981. }
  87982. }
  87983. /** @hidden */
  87984. PhysicsViewer.prototype._updateDebugMeshes = function () {
  87985. var plugin = this._physicsEnginePlugin;
  87986. for (var i = 0; i < this._numMeshes; i++) {
  87987. var impostor = this._impostors[i];
  87988. if (!impostor) {
  87989. continue;
  87990. }
  87991. if (impostor.isDisposed) {
  87992. this.hideImpostor(this._impostors[i--]);
  87993. }
  87994. else {
  87995. var mesh = this._meshes[i];
  87996. if (mesh && plugin) {
  87997. plugin.syncMeshWithImpostor(mesh, impostor);
  87998. }
  87999. }
  88000. }
  88001. };
  88002. /**
  88003. * Renders a specified physic impostor
  88004. * @param impostor defines the impostor to render
  88005. */
  88006. PhysicsViewer.prototype.showImpostor = function (impostor) {
  88007. if (!this._scene) {
  88008. return;
  88009. }
  88010. for (var i = 0; i < this._numMeshes; i++) {
  88011. if (this._impostors[i] == impostor) {
  88012. return;
  88013. }
  88014. }
  88015. var debugMesh = this._getDebugMesh(impostor, this._scene);
  88016. if (debugMesh) {
  88017. this._impostors[this._numMeshes] = impostor;
  88018. this._meshes[this._numMeshes] = debugMesh;
  88019. if (this._numMeshes === 0) {
  88020. this._renderFunction = this._updateDebugMeshes.bind(this);
  88021. this._scene.registerBeforeRender(this._renderFunction);
  88022. }
  88023. this._numMeshes++;
  88024. }
  88025. };
  88026. /**
  88027. * Hides a specified physic impostor
  88028. * @param impostor defines the impostor to hide
  88029. */
  88030. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  88031. if (!impostor || !this._scene) {
  88032. return;
  88033. }
  88034. var removed = false;
  88035. for (var i = 0; i < this._numMeshes; i++) {
  88036. if (this._impostors[i] == impostor) {
  88037. var mesh = this._meshes[i];
  88038. if (!mesh) {
  88039. continue;
  88040. }
  88041. this._scene.removeMesh(mesh);
  88042. mesh.dispose();
  88043. this._numMeshes--;
  88044. if (this._numMeshes > 0) {
  88045. this._meshes[i] = this._meshes[this._numMeshes];
  88046. this._impostors[i] = this._impostors[this._numMeshes];
  88047. this._meshes[this._numMeshes] = null;
  88048. this._impostors[this._numMeshes] = null;
  88049. }
  88050. else {
  88051. this._meshes[0] = null;
  88052. this._impostors[0] = null;
  88053. }
  88054. removed = true;
  88055. break;
  88056. }
  88057. }
  88058. if (removed && this._numMeshes === 0) {
  88059. this._scene.unregisterBeforeRender(this._renderFunction);
  88060. }
  88061. };
  88062. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  88063. if (!this._debugMaterial) {
  88064. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  88065. this._debugMaterial.wireframe = true;
  88066. }
  88067. return this._debugMaterial;
  88068. };
  88069. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  88070. if (!this._debugBoxMesh) {
  88071. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  88072. this._debugBoxMesh.renderingGroupId = 1;
  88073. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88074. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  88075. scene.removeMesh(this._debugBoxMesh);
  88076. }
  88077. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  88078. };
  88079. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  88080. if (!this._debugSphereMesh) {
  88081. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  88082. this._debugSphereMesh.renderingGroupId = 1;
  88083. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88084. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  88085. scene.removeMesh(this._debugSphereMesh);
  88086. }
  88087. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  88088. };
  88089. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  88090. var mesh = null;
  88091. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  88092. mesh = this._getDebugBoxMesh(scene);
  88093. impostor.getBoxSizeToRef(mesh.scaling);
  88094. }
  88095. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  88096. mesh = this._getDebugSphereMesh(scene);
  88097. var radius = impostor.getRadius();
  88098. mesh.scaling.x = radius * 2;
  88099. mesh.scaling.y = radius * 2;
  88100. mesh.scaling.z = radius * 2;
  88101. }
  88102. return mesh;
  88103. };
  88104. /** Releases all resources */
  88105. PhysicsViewer.prototype.dispose = function () {
  88106. for (var i = 0; i < this._numMeshes; i++) {
  88107. this.hideImpostor(this._impostors[i]);
  88108. }
  88109. if (this._debugBoxMesh) {
  88110. this._debugBoxMesh.dispose();
  88111. }
  88112. if (this._debugSphereMesh) {
  88113. this._debugSphereMesh.dispose();
  88114. }
  88115. if (this._debugMaterial) {
  88116. this._debugMaterial.dispose();
  88117. }
  88118. this._impostors.length = 0;
  88119. this._scene = null;
  88120. this._physicsEnginePlugin = null;
  88121. };
  88122. return PhysicsViewer;
  88123. }());
  88124. Debug.PhysicsViewer = PhysicsViewer;
  88125. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88126. })(BABYLON || (BABYLON = {}));
  88127. //# sourceMappingURL=babylon.physicsViewer.js.map
  88128. var BABYLON;
  88129. (function (BABYLON) {
  88130. var BoundingBoxRenderer = /** @class */ (function () {
  88131. function BoundingBoxRenderer(scene) {
  88132. this.frontColor = new BABYLON.Color3(1, 1, 1);
  88133. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  88134. this.showBackLines = true;
  88135. this.renderList = new BABYLON.SmartArray(32);
  88136. this._vertexBuffers = {};
  88137. this._scene = scene;
  88138. }
  88139. BoundingBoxRenderer.prototype._prepareRessources = function () {
  88140. if (this._colorShader) {
  88141. return;
  88142. }
  88143. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  88144. attributes: [BABYLON.VertexBuffer.PositionKind],
  88145. uniforms: ["world", "viewProjection", "color"]
  88146. });
  88147. var engine = this._scene.getEngine();
  88148. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88149. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88150. this._createIndexBuffer();
  88151. };
  88152. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88153. var engine = this._scene.getEngine();
  88154. 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]);
  88155. };
  88156. BoundingBoxRenderer.prototype._rebuild = function () {
  88157. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88158. if (vb) {
  88159. vb._rebuild();
  88160. }
  88161. this._createIndexBuffer();
  88162. };
  88163. BoundingBoxRenderer.prototype.reset = function () {
  88164. this.renderList.reset();
  88165. };
  88166. BoundingBoxRenderer.prototype.render = function () {
  88167. if (this.renderList.length === 0) {
  88168. return;
  88169. }
  88170. this._prepareRessources();
  88171. if (!this._colorShader.isReady()) {
  88172. return;
  88173. }
  88174. var engine = this._scene.getEngine();
  88175. engine.setDepthWrite(false);
  88176. this._colorShader._preBind();
  88177. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88178. var boundingBox = this.renderList.data[boundingBoxIndex];
  88179. var min = boundingBox.minimum;
  88180. var max = boundingBox.maximum;
  88181. var diff = max.subtract(min);
  88182. var median = min.add(diff.scale(0.5));
  88183. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88184. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88185. .multiply(boundingBox.getWorldMatrix());
  88186. // VBOs
  88187. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88188. if (this.showBackLines) {
  88189. // Back
  88190. engine.setDepthFunctionToGreaterOrEqual();
  88191. this._scene.resetCachedMaterial();
  88192. this._colorShader.setColor4("color", this.backColor.toColor4());
  88193. this._colorShader.bind(worldMatrix);
  88194. // Draw order
  88195. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88196. }
  88197. // Front
  88198. engine.setDepthFunctionToLess();
  88199. this._scene.resetCachedMaterial();
  88200. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88201. this._colorShader.bind(worldMatrix);
  88202. // Draw order
  88203. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88204. }
  88205. this._colorShader.unbind();
  88206. engine.setDepthFunctionToLessOrEqual();
  88207. engine.setDepthWrite(true);
  88208. };
  88209. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88210. this._prepareRessources();
  88211. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88212. return;
  88213. }
  88214. var engine = this._scene.getEngine();
  88215. engine.setDepthWrite(false);
  88216. engine.setColorWrite(false);
  88217. this._colorShader._preBind();
  88218. var boundingBox = mesh._boundingInfo.boundingBox;
  88219. var min = boundingBox.minimum;
  88220. var max = boundingBox.maximum;
  88221. var diff = max.subtract(min);
  88222. var median = min.add(diff.scale(0.5));
  88223. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88224. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88225. .multiply(boundingBox.getWorldMatrix());
  88226. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88227. engine.setDepthFunctionToLess();
  88228. this._scene.resetCachedMaterial();
  88229. this._colorShader.bind(worldMatrix);
  88230. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88231. this._colorShader.unbind();
  88232. engine.setDepthFunctionToLessOrEqual();
  88233. engine.setDepthWrite(true);
  88234. engine.setColorWrite(true);
  88235. };
  88236. BoundingBoxRenderer.prototype.dispose = function () {
  88237. if (!this._colorShader) {
  88238. return;
  88239. }
  88240. this.renderList.dispose();
  88241. this._colorShader.dispose();
  88242. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88243. if (buffer) {
  88244. buffer.dispose();
  88245. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88246. }
  88247. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88248. };
  88249. return BoundingBoxRenderer;
  88250. }());
  88251. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88252. })(BABYLON || (BABYLON = {}));
  88253. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88254. var BABYLON;
  88255. (function (BABYLON) {
  88256. /**
  88257. * Renders a layer on top of an existing scene
  88258. */
  88259. var UtilityLayerRenderer = /** @class */ (function () {
  88260. /**
  88261. * Instantiates a UtilityLayerRenderer
  88262. * @param originalScene the original scene that will be rendered on top of
  88263. */
  88264. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88265. var _this = this;
  88266. this.originalScene = originalScene;
  88267. this._pointerCaptures = {};
  88268. this._lastPointerEvents = {};
  88269. /**
  88270. * If the utility layer should automatically be rendered on top of existing scene
  88271. */
  88272. this.shouldRender = true;
  88273. /**
  88274. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88275. */
  88276. this.onlyCheckPointerDownEvents = true;
  88277. /**
  88278. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88279. */
  88280. this.processAllEvents = false;
  88281. /**
  88282. * Observable raised when the pointer move from the utility layer scene to the main scene
  88283. */
  88284. this.onPointerOutObservable = new BABYLON.Observable();
  88285. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88286. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88287. originalScene.getEngine().scenes.pop();
  88288. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88289. this.utilityLayerScene.detachControl();
  88290. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88291. if (!_this.processAllEvents) {
  88292. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88293. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88294. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88295. return;
  88296. }
  88297. }
  88298. var pointerEvent = (prePointerInfo.event);
  88299. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88300. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88301. return;
  88302. }
  88303. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88304. if (!prePointerInfo.ray && utilityScenePick) {
  88305. prePointerInfo.ray = utilityScenePick.ray;
  88306. }
  88307. // always fire the prepointer oversvable
  88308. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88309. // allow every non pointer down event to flow to the utility layer
  88310. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88311. if (!prePointerInfo.skipOnPointerObservable) {
  88312. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88313. }
  88314. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88315. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88316. }
  88317. return;
  88318. }
  88319. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88320. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88321. if (utilityScenePick && utilityScenePick.hit) {
  88322. if (!prePointerInfo.skipOnPointerObservable) {
  88323. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88324. }
  88325. prePointerInfo.skipOnPointerObservable = true;
  88326. }
  88327. }
  88328. else {
  88329. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88330. var pointerEvent_1 = (prePointerInfo.event);
  88331. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88332. if (originalScenePick && utilityScenePick) {
  88333. // No pick in utility scene
  88334. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88335. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88336. // We touched an utility mesh present in the main scene
  88337. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88338. prePointerInfo.skipOnPointerObservable = true;
  88339. }
  88340. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88341. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88342. }
  88343. }
  88344. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88345. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88346. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88347. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88348. }
  88349. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88350. // We have a pick in both scenes but main is closer than utility
  88351. // We touched an utility mesh present in the main scene
  88352. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88353. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88354. prePointerInfo.skipOnPointerObservable = true;
  88355. }
  88356. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88357. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88358. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88359. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88360. }
  88361. }
  88362. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88363. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88364. }
  88365. }
  88366. }
  88367. });
  88368. // Render directly on top of existing scene without clearing
  88369. this.utilityLayerScene.autoClear = false;
  88370. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88371. if (_this.shouldRender) {
  88372. _this.render();
  88373. }
  88374. });
  88375. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88376. _this.dispose();
  88377. });
  88378. this._updateCamera();
  88379. }
  88380. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88381. get: function () {
  88382. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88383. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88384. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88385. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88386. });
  88387. }
  88388. return UtilityLayerRenderer._DefaultUtilityLayer;
  88389. },
  88390. enumerable: true,
  88391. configurable: true
  88392. });
  88393. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88394. if (!prePointerInfo.skipOnPointerObservable) {
  88395. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88396. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88397. }
  88398. };
  88399. /**
  88400. * Renders the utility layers scene on top of the original scene
  88401. */
  88402. UtilityLayerRenderer.prototype.render = function () {
  88403. this._updateCamera();
  88404. this.utilityLayerScene.render(false);
  88405. };
  88406. /**
  88407. * Disposes of the renderer
  88408. */
  88409. UtilityLayerRenderer.prototype.dispose = function () {
  88410. this.onPointerOutObservable.clear();
  88411. if (this._afterRenderObserver) {
  88412. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88413. }
  88414. if (this._sceneDisposeObserver) {
  88415. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88416. }
  88417. if (this._originalPointerObserver) {
  88418. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88419. }
  88420. this.utilityLayerScene.dispose();
  88421. };
  88422. UtilityLayerRenderer.prototype._updateCamera = function () {
  88423. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88424. };
  88425. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88426. return UtilityLayerRenderer;
  88427. }());
  88428. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88429. })(BABYLON || (BABYLON = {}));
  88430. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88431. //# sourceMappingURL=babylon.behavior.js.map
  88432. var BABYLON;
  88433. (function (BABYLON) {
  88434. /**
  88435. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88436. */
  88437. var PointerDragBehavior = /** @class */ (function () {
  88438. /**
  88439. * Creates a pointer drag behavior that can be attached to a mesh
  88440. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  88441. */
  88442. function PointerDragBehavior(options) {
  88443. this.options = options;
  88444. /**
  88445. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88446. */
  88447. this.currentDraggingPointerID = -1;
  88448. /**
  88449. * If the behavior is currently in a dragging state
  88450. */
  88451. this.dragging = false;
  88452. /**
  88453. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  88454. */
  88455. this.dragDeltaRatio = 0.2;
  88456. /**
  88457. * If the drag plane orientation should be updated during the dragging (Default: true)
  88458. */
  88459. this.updateDragPlane = true;
  88460. // Debug mode will display drag planes to help visualize behavior
  88461. this._debugMode = false;
  88462. this._moving = false;
  88463. /**
  88464. * Fires each time the attached mesh is dragged with the pointer
  88465. * * delta between last drag position and current drag position in world space
  88466. * * dragDistance along the drag axis
  88467. * * dragPlaneNormal normal of the current drag plane used during the drag
  88468. * * dragPlanePoint in world space where the drag intersects the drag plane
  88469. */
  88470. this.onDragObservable = new BABYLON.Observable();
  88471. /**
  88472. * Fires each time a drag begins (eg. mouse down on mesh)
  88473. */
  88474. this.onDragStartObservable = new BABYLON.Observable();
  88475. /**
  88476. * Fires each time a drag ends (eg. mouse release after drag)
  88477. */
  88478. this.onDragEndObservable = new BABYLON.Observable();
  88479. /**
  88480. * If the attached mesh should be moved when dragged
  88481. */
  88482. this.moveAttached = true;
  88483. /**
  88484. * If the drag behavior will react to drag events (Default: true)
  88485. */
  88486. this.enabled = true;
  88487. /**
  88488. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88489. */
  88490. this.useObjectOrienationForDragging = true;
  88491. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88492. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88493. // Variables to avoid instantiation in the below method
  88494. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88495. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88496. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88497. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88498. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88499. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88500. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88501. var optionCount = 0;
  88502. if (options === undefined) {
  88503. options = {};
  88504. }
  88505. if (options.dragAxis) {
  88506. optionCount++;
  88507. }
  88508. if (options.dragPlaneNormal) {
  88509. optionCount++;
  88510. }
  88511. if (optionCount > 1) {
  88512. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88513. }
  88514. }
  88515. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88516. /**
  88517. * The name of the behavior
  88518. */
  88519. get: function () {
  88520. return "PointerDrag";
  88521. },
  88522. enumerable: true,
  88523. configurable: true
  88524. });
  88525. /**
  88526. * Initializes the behavior
  88527. */
  88528. PointerDragBehavior.prototype.init = function () { };
  88529. /**
  88530. * Attaches the drag behavior the passed in mesh
  88531. * @param ownerNode The mesh that will be dragged around once attached
  88532. */
  88533. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88534. var _this = this;
  88535. this._scene = ownerNode.getScene();
  88536. this._attachedNode = ownerNode;
  88537. // Initialize drag plane to not interfere with existing scene
  88538. if (!PointerDragBehavior._planeScene) {
  88539. if (this._debugMode) {
  88540. PointerDragBehavior._planeScene = this._scene;
  88541. }
  88542. else {
  88543. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88544. this._scene.getEngine().scenes.pop();
  88545. }
  88546. }
  88547. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88548. // State of the drag
  88549. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88550. var delta = new BABYLON.Vector3(0, 0, 0);
  88551. var dragLength = 0;
  88552. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88553. var pickPredicate = function (m) {
  88554. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88555. };
  88556. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88557. if (!_this.enabled) {
  88558. return;
  88559. }
  88560. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88561. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88562. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88563. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88564. if (pickedPoint) {
  88565. _this.dragging = true;
  88566. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88567. _this.lastDragPosition.copyFrom(pickedPoint);
  88568. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88569. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88570. }
  88571. }
  88572. }
  88573. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88574. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88575. _this.releaseDrag();
  88576. }
  88577. }
  88578. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88579. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88580. _this._moving = true;
  88581. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88582. if (pickedPoint) {
  88583. if (_this.updateDragPlane) {
  88584. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88585. }
  88586. // depending on the drag mode option drag accordingly
  88587. if (_this.options.dragAxis) {
  88588. // Convert local drag axis to world
  88589. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88590. // Project delta drag from the drag plane onto the drag axis
  88591. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88592. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88593. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88594. }
  88595. else {
  88596. dragLength = delta.length();
  88597. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88598. }
  88599. targetPosition.addInPlace(delta);
  88600. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88601. _this.lastDragPosition.copyFrom(pickedPoint);
  88602. }
  88603. }
  88604. }
  88605. });
  88606. this._scene.onBeforeRenderObservable.add(function () {
  88607. if (_this._moving && _this.moveAttached) {
  88608. // Slowly move mesh to avoid jitter
  88609. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88610. _this._tmpVector.scaleInPlace(0.2);
  88611. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88612. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88613. }
  88614. });
  88615. };
  88616. PointerDragBehavior.prototype.releaseDrag = function () {
  88617. this.dragging = false;
  88618. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88619. this.currentDraggingPointerID = -1;
  88620. this._moving = false;
  88621. };
  88622. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88623. var _this = this;
  88624. if (!ray) {
  88625. return null;
  88626. }
  88627. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88628. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88629. return pickResult.pickedPoint;
  88630. }
  88631. else {
  88632. return null;
  88633. }
  88634. };
  88635. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88636. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88637. this._pointA.copyFrom(dragPlanePosition);
  88638. if (this.options.dragAxis) {
  88639. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  88640. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88641. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88642. ray.origin.subtractToRef(this._pointA, this._pointC);
  88643. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88644. // Get perpendicular line from direction to camera and drag axis
  88645. this._pointB.subtractToRef(this._pointA, this._lineA);
  88646. this._pointC.subtractToRef(this._pointA, this._lineB);
  88647. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88648. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88649. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88650. this._lookAt.normalize();
  88651. this._dragPlane.position.copyFrom(this._pointA);
  88652. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88653. this._dragPlane.lookAt(this._lookAt);
  88654. }
  88655. else if (this.options.dragPlaneNormal) {
  88656. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88657. this._dragPlane.position.copyFrom(this._pointA);
  88658. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88659. this._dragPlane.lookAt(this._lookAt);
  88660. }
  88661. else {
  88662. this._dragPlane.position.copyFrom(this._pointA);
  88663. this._dragPlane.lookAt(ray.origin);
  88664. }
  88665. this._dragPlane.computeWorldMatrix(true);
  88666. };
  88667. /**
  88668. * Detaches the behavior from the mesh
  88669. */
  88670. PointerDragBehavior.prototype.detach = function () {
  88671. if (this._pointerObserver) {
  88672. this._scene.onPointerObservable.remove(this._pointerObserver);
  88673. }
  88674. };
  88675. return PointerDragBehavior;
  88676. }());
  88677. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88678. })(BABYLON || (BABYLON = {}));
  88679. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88680. var BABYLON;
  88681. (function (BABYLON) {
  88682. /**
  88683. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88684. */
  88685. var MultiPointerScaleBehavior = /** @class */ (function () {
  88686. function MultiPointerScaleBehavior() {
  88687. this._startDistance = 0;
  88688. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88689. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88690. this._sceneRenderObserver = null;
  88691. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88692. this._dragBehaviorA.moveAttached = false;
  88693. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88694. this._dragBehaviorB.moveAttached = false;
  88695. }
  88696. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88697. /**
  88698. * The name of the behavior
  88699. */
  88700. get: function () {
  88701. return "MultiPointerScale";
  88702. },
  88703. enumerable: true,
  88704. configurable: true
  88705. });
  88706. /**
  88707. * Initializes the behavior
  88708. */
  88709. MultiPointerScaleBehavior.prototype.init = function () { };
  88710. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88711. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88712. };
  88713. /**
  88714. * Attaches the scale behavior the passed in mesh
  88715. * @param ownerNode The mesh that will be scaled around once attached
  88716. */
  88717. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88718. var _this = this;
  88719. this._ownerNode = ownerNode;
  88720. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88721. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88722. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88723. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88724. _this._dragBehaviorA.releaseDrag();
  88725. }
  88726. else {
  88727. _this._initialScale.copyFrom(ownerNode.scaling);
  88728. _this._startDistance = _this._getCurrentDistance();
  88729. }
  88730. }
  88731. });
  88732. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88733. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88734. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88735. _this._dragBehaviorB.releaseDrag();
  88736. }
  88737. else {
  88738. _this._initialScale.copyFrom(ownerNode.scaling);
  88739. _this._startDistance = _this._getCurrentDistance();
  88740. }
  88741. }
  88742. });
  88743. // Once both drag behaviors are active scale based on the distance between the two pointers
  88744. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88745. behavior.onDragObservable.add(function () {
  88746. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88747. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88748. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  88749. }
  88750. });
  88751. });
  88752. ownerNode.addBehavior(this._dragBehaviorA);
  88753. ownerNode.addBehavior(this._dragBehaviorB);
  88754. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88755. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88756. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88757. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  88758. if (change.length() > 0.01) {
  88759. ownerNode.scaling.addInPlace(change);
  88760. }
  88761. }
  88762. });
  88763. };
  88764. /**
  88765. * Detaches the behavior from the mesh
  88766. */
  88767. MultiPointerScaleBehavior.prototype.detach = function () {
  88768. var _this = this;
  88769. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88770. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88771. behavior.onDragStartObservable.clear();
  88772. behavior.onDragObservable.clear();
  88773. _this._ownerNode.removeBehavior(behavior);
  88774. });
  88775. };
  88776. return MultiPointerScaleBehavior;
  88777. }());
  88778. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  88779. })(BABYLON || (BABYLON = {}));
  88780. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  88781. var BABYLON;
  88782. (function (BABYLON) {
  88783. /**
  88784. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  88785. */
  88786. var SixDofDragBehavior = /** @class */ (function () {
  88787. function SixDofDragBehavior() {
  88788. this._sceneRenderObserver = null;
  88789. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  88790. this._moving = false;
  88791. this._startingOrientation = new BABYLON.Quaternion();
  88792. /**
  88793. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 5)
  88794. */
  88795. this.zDragFactor = 5;
  88796. /**
  88797. * If the behavior is currently in a dragging state
  88798. */
  88799. this.dragging = false;
  88800. /**
  88801. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  88802. */
  88803. this.dragDeltaRatio = 0.2;
  88804. /**
  88805. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88806. */
  88807. this.currentDraggingPointerID = -1;
  88808. }
  88809. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  88810. /**
  88811. * The name of the behavior
  88812. */
  88813. get: function () {
  88814. return "SixDofDrag";
  88815. },
  88816. enumerable: true,
  88817. configurable: true
  88818. });
  88819. /**
  88820. * Initializes the behavior
  88821. */
  88822. SixDofDragBehavior.prototype.init = function () { };
  88823. /**
  88824. * Attaches the scale behavior the passed in mesh
  88825. * @param ownerNode The mesh that will be scaled around once attached
  88826. */
  88827. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88828. var _this = this;
  88829. this._ownerNode = ownerNode;
  88830. this._scene = this._ownerNode.getScene();
  88831. if (!SixDofDragBehavior._virtualScene) {
  88832. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88833. this._scene.getEngine().scenes.pop();
  88834. }
  88835. var pickedMesh = null;
  88836. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88837. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88838. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88839. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88840. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88841. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88842. var pickPredicate = function (m) {
  88843. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88844. };
  88845. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88846. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88847. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88848. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88849. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88850. // Set position and orientation of the controller
  88851. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88852. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88853. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88854. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88855. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88856. if (!pickedMesh.rotationQuaternion) {
  88857. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  88858. }
  88859. var oldParent = pickedMesh.parent;
  88860. pickedMesh.setParent(null);
  88861. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  88862. pickedMesh.setParent(oldParent);
  88863. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88864. // Update state
  88865. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88866. _this.dragging = true;
  88867. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88868. }
  88869. }
  88870. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88871. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88872. _this.dragging = false;
  88873. _this._moving = false;
  88874. _this.currentDraggingPointerID = -1;
  88875. pickedMesh = null;
  88876. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88877. }
  88878. }
  88879. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88880. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  88881. // Calculate controller drag distance in controller space
  88882. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  88883. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88884. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  88885. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88886. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  88887. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  88888. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  88889. if (_this._virtualDragMesh.position.z < 0) {
  88890. _this._virtualDragMesh.position.z = 0;
  88891. }
  88892. // Update the controller position
  88893. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88894. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88895. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88896. // Move the virtualObjectsPosition into the picked mesh's space if needed
  88897. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88898. if (pickedMesh.parent) {
  88899. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  88900. }
  88901. if (!_this._moving) {
  88902. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  88903. }
  88904. _this._moving = true;
  88905. }
  88906. }
  88907. });
  88908. var tmpQuaternion = new BABYLON.Quaternion();
  88909. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88910. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88911. if (_this.dragging && _this._moving && pickedMesh) {
  88912. // Slowly move mesh to avoid jitter
  88913. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  88914. // Get change in rotation
  88915. tmpQuaternion.copyFrom(_this._startingOrientation);
  88916. tmpQuaternion.x = -tmpQuaternion.x;
  88917. tmpQuaternion.y = -tmpQuaternion.y;
  88918. tmpQuaternion.z = -tmpQuaternion.z;
  88919. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  88920. // Convert change in rotation to only y axis rotation
  88921. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  88922. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  88923. // Slowly move mesh to avoid jitter
  88924. var oldParent = pickedMesh.parent;
  88925. pickedMesh.setParent(null);
  88926. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  88927. pickedMesh.setParent(oldParent);
  88928. }
  88929. });
  88930. };
  88931. /**
  88932. * Detaches the behavior from the mesh
  88933. */
  88934. SixDofDragBehavior.prototype.detach = function () {
  88935. this._scene.onPointerObservable.remove(this._pointerObserver);
  88936. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88937. this._virtualOriginMesh.dispose();
  88938. this._virtualDragMesh.dispose();
  88939. };
  88940. return SixDofDragBehavior;
  88941. }());
  88942. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  88943. })(BABYLON || (BABYLON = {}));
  88944. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  88945. var BABYLON;
  88946. (function (BABYLON) {
  88947. /**
  88948. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  88949. */
  88950. var Gizmo = /** @class */ (function () {
  88951. /**
  88952. * Creates a gizmo
  88953. * @param gizmoLayer The utility layer the gizmo will be added to
  88954. */
  88955. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  88956. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  88957. var _this = this;
  88958. this.gizmoLayer = gizmoLayer;
  88959. /**
  88960. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  88961. */
  88962. this.updateGizmoRotationToMatchAttachedMesh = true;
  88963. /**
  88964. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  88965. */
  88966. this.updateGizmoPositionToMatchAttachedMesh = true;
  88967. /**
  88968. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  88969. */
  88970. this._updateScale = true;
  88971. this._interactionsEnabled = true;
  88972. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  88973. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  88974. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  88975. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  88976. _this._rootMesh.scaling.set(dist, dist, dist);
  88977. }
  88978. if (_this.attachedMesh) {
  88979. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88980. if (!_this._rootMesh.rotationQuaternion) {
  88981. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  88982. }
  88983. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  88984. }
  88985. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  88986. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  88987. }
  88988. }
  88989. });
  88990. this.attachedMesh = null;
  88991. }
  88992. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  88993. /**
  88994. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  88995. * * When set, interactions will be enabled
  88996. */
  88997. get: function () {
  88998. return this._attachedMesh;
  88999. },
  89000. set: function (value) {
  89001. this._attachedMesh = value;
  89002. this._rootMesh.setEnabled(value ? true : false);
  89003. this._attachedMeshChanged(value);
  89004. },
  89005. enumerable: true,
  89006. configurable: true
  89007. });
  89008. Gizmo.prototype._attachedMeshChanged = function (value) {
  89009. };
  89010. /**
  89011. * Disposes of the gizmo
  89012. */
  89013. Gizmo.prototype.dispose = function () {
  89014. this._rootMesh.dispose();
  89015. if (this._beforeRenderObserver) {
  89016. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89017. }
  89018. };
  89019. return Gizmo;
  89020. }());
  89021. BABYLON.Gizmo = Gizmo;
  89022. })(BABYLON || (BABYLON = {}));
  89023. //# sourceMappingURL=babylon.gizmo.js.map
  89024. var BABYLON;
  89025. (function (BABYLON) {
  89026. /**
  89027. * Single axis drag gizmo
  89028. */
  89029. var AxisDragGizmo = /** @class */ (function (_super) {
  89030. __extends(AxisDragGizmo, _super);
  89031. /**
  89032. * Creates an AxisDragGizmo
  89033. * @param gizmoLayer The utility layer the gizmo will be added to
  89034. * @param dragAxis The axis which the gizmo will be able to drag on
  89035. * @param color The color of the gizmo
  89036. */
  89037. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89038. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89039. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89040. var _this = _super.call(this, gizmoLayer) || this;
  89041. _this._pointerObserver = null;
  89042. /**
  89043. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89044. */
  89045. _this.snapDistance = 0;
  89046. /**
  89047. * Event that fires each time the gizmo snaps to a new location.
  89048. * * snapDistance is the the change in distance
  89049. */
  89050. _this.onSnapObservable = new BABYLON.Observable();
  89051. // Create Material
  89052. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89053. coloredMaterial.disableLighting = true;
  89054. coloredMaterial.emissiveColor = color;
  89055. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89056. hoverMaterial.disableLighting = true;
  89057. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89058. // Build mesh on root node
  89059. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89060. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89061. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89062. arrow.addChild(arrowMesh);
  89063. arrow.addChild(arrowTail);
  89064. // Position arrow pointing in its drag axis
  89065. arrowMesh.scaling.scaleInPlace(0.05);
  89066. arrowMesh.material = coloredMaterial;
  89067. arrowMesh.rotation.x = Math.PI / 2;
  89068. arrowMesh.position.z += 0.3;
  89069. arrowTail.rotation.x = Math.PI / 2;
  89070. arrowTail.material = coloredMaterial;
  89071. arrowTail.position.z += 0.15;
  89072. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89073. _this._rootMesh.addChild(arrow);
  89074. var currentSnapDragDistance = 0;
  89075. var tmpVector = new BABYLON.Vector3();
  89076. var tmpSnapEvent = { snapDistance: 0 };
  89077. // Add drag behavior to handle events when the gizmo is dragged
  89078. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89079. _this._dragBehavior.moveAttached = false;
  89080. _this._rootMesh.addBehavior(_this._dragBehavior);
  89081. _this._dragBehavior.onDragObservable.add(function (event) {
  89082. if (_this.attachedMesh) {
  89083. // Snapping logic
  89084. if (_this.snapDistance == 0) {
  89085. _this.attachedMesh.position.addInPlace(event.delta);
  89086. }
  89087. else {
  89088. currentSnapDragDistance += event.dragDistance;
  89089. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89090. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89091. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89092. event.delta.normalizeToRef(tmpVector);
  89093. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89094. _this.attachedMesh.position.addInPlace(tmpVector);
  89095. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89096. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89097. }
  89098. }
  89099. }
  89100. });
  89101. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89102. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89103. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89104. m.material = hoverMaterial;
  89105. });
  89106. }
  89107. else {
  89108. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89109. m.material = coloredMaterial;
  89110. });
  89111. }
  89112. });
  89113. return _this;
  89114. }
  89115. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89116. if (this._dragBehavior) {
  89117. this._dragBehavior.enabled = value ? true : false;
  89118. }
  89119. };
  89120. /**
  89121. * Disposes of the gizmo
  89122. */
  89123. AxisDragGizmo.prototype.dispose = function () {
  89124. this.onSnapObservable.clear();
  89125. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89126. this._dragBehavior.detach();
  89127. _super.prototype.dispose.call(this);
  89128. };
  89129. return AxisDragGizmo;
  89130. }(BABYLON.Gizmo));
  89131. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89132. })(BABYLON || (BABYLON = {}));
  89133. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89134. var BABYLON;
  89135. (function (BABYLON) {
  89136. /**
  89137. * Single axis scale gizmo
  89138. */
  89139. var AxisScaleGizmo = /** @class */ (function (_super) {
  89140. __extends(AxisScaleGizmo, _super);
  89141. /**
  89142. * Creates an AxisScaleGizmo
  89143. * @param gizmoLayer The utility layer the gizmo will be added to
  89144. * @param dragAxis The axis which the gizmo will be able to scale on
  89145. * @param color The color of the gizmo
  89146. */
  89147. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89148. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89149. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89150. var _this = _super.call(this, gizmoLayer) || this;
  89151. _this._pointerObserver = null;
  89152. /**
  89153. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89154. */
  89155. _this.snapDistance = 0;
  89156. /**
  89157. * Event that fires each time the gizmo snaps to a new location.
  89158. * * snapDistance is the the change in distance
  89159. */
  89160. _this.onSnapObservable = new BABYLON.Observable();
  89161. // Create Material
  89162. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89163. coloredMaterial.disableLighting = true;
  89164. coloredMaterial.emissiveColor = color;
  89165. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89166. hoverMaterial.disableLighting = true;
  89167. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89168. // Build mesh on root node
  89169. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89170. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89171. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89172. arrow.addChild(arrowMesh);
  89173. arrow.addChild(arrowTail);
  89174. // Position arrow pointing in its drag axis
  89175. arrowMesh.scaling.scaleInPlace(0.1);
  89176. arrowMesh.material = coloredMaterial;
  89177. arrowMesh.rotation.x = Math.PI / 2;
  89178. arrowMesh.position.z += 0.3;
  89179. arrowTail.rotation.x = Math.PI / 2;
  89180. arrowTail.material = coloredMaterial;
  89181. arrowTail.position.z += 0.15;
  89182. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89183. _this._rootMesh.addChild(arrow);
  89184. // Add drag behavior to handle events when the gizmo is dragged
  89185. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89186. _this._dragBehavior.moveAttached = false;
  89187. _this._rootMesh.addBehavior(_this._dragBehavior);
  89188. var currentSnapDragDistance = 0;
  89189. var tmpVector = new BABYLON.Vector3();
  89190. var tmpSnapEvent = { snapDistance: 0 };
  89191. _this._dragBehavior.onDragObservable.add(function (event) {
  89192. if (_this.attachedMesh) {
  89193. // Snapping logic
  89194. var snapped = false;
  89195. var dragSteps = 0;
  89196. if (_this.snapDistance == 0) {
  89197. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89198. }
  89199. else {
  89200. currentSnapDragDistance += event.dragDistance;
  89201. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89202. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89203. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89204. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89205. snapped = true;
  89206. }
  89207. else {
  89208. tmpVector.scaleInPlace(0);
  89209. }
  89210. }
  89211. var invertCount = 0;
  89212. if (_this.attachedMesh.scaling["x"] < 0) {
  89213. invertCount++;
  89214. }
  89215. if (_this.attachedMesh.scaling["y"] < 0) {
  89216. invertCount++;
  89217. }
  89218. if (_this.attachedMesh.scaling["z"] < 0) {
  89219. invertCount++;
  89220. }
  89221. if (invertCount % 2 == 0) {
  89222. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89223. }
  89224. else {
  89225. _this.attachedMesh.scaling.subtractInPlace(tmpVector);
  89226. }
  89227. if (snapped) {
  89228. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89229. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89230. }
  89231. }
  89232. });
  89233. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89234. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89235. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89236. m.material = hoverMaterial;
  89237. });
  89238. }
  89239. else {
  89240. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89241. m.material = coloredMaterial;
  89242. });
  89243. }
  89244. });
  89245. return _this;
  89246. }
  89247. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89248. if (this._dragBehavior) {
  89249. this._dragBehavior.enabled = value ? true : false;
  89250. }
  89251. };
  89252. /**
  89253. * Disposes of the gizmo
  89254. */
  89255. AxisScaleGizmo.prototype.dispose = function () {
  89256. this.onSnapObservable.clear();
  89257. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89258. this._dragBehavior.detach();
  89259. _super.prototype.dispose.call(this);
  89260. };
  89261. return AxisScaleGizmo;
  89262. }(BABYLON.Gizmo));
  89263. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89264. })(BABYLON || (BABYLON = {}));
  89265. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89266. var BABYLON;
  89267. (function (BABYLON) {
  89268. /**
  89269. * Single plane rotation gizmo
  89270. */
  89271. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89272. __extends(PlaneRotationGizmo, _super);
  89273. /**
  89274. * Creates a PlaneRotationGizmo
  89275. * @param gizmoLayer The utility layer the gizmo will be added to
  89276. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89277. * @param color The color of the gizmo
  89278. */
  89279. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89280. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89281. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89282. var _this = _super.call(this, gizmoLayer) || this;
  89283. _this._pointerObserver = null;
  89284. /**
  89285. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89286. */
  89287. _this.snapDistance = 0;
  89288. /**
  89289. * Event that fires each time the gizmo snaps to a new location.
  89290. * * snapDistance is the the change in distance
  89291. */
  89292. _this.onSnapObservable = new BABYLON.Observable();
  89293. // Create Material
  89294. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89295. coloredMaterial.disableLighting = true;
  89296. coloredMaterial.emissiveColor = color;
  89297. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89298. hoverMaterial.disableLighting = true;
  89299. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89300. // Build mesh on root node
  89301. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89302. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89303. // Position arrow pointing in its drag axis
  89304. rotationMesh.scaling.scaleInPlace(0.1);
  89305. rotationMesh.material = coloredMaterial;
  89306. rotationMesh.rotation.x = Math.PI / 2;
  89307. parentMesh.addChild(rotationMesh);
  89308. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89309. _this._rootMesh.addChild(parentMesh);
  89310. // Add drag behavior to handle events when the gizmo is dragged
  89311. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89312. _this._dragBehavior.moveAttached = false;
  89313. _this._rootMesh.addBehavior(_this._dragBehavior);
  89314. var lastDragPosition = null;
  89315. _this._dragBehavior.onDragStartObservable.add(function (e) {
  89316. if (_this.attachedMesh) {
  89317. lastDragPosition = e.dragPlanePoint;
  89318. }
  89319. });
  89320. var rotationMatrix = new BABYLON.Matrix();
  89321. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89322. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89323. var tmpSnapEvent = { snapDistance: 0 };
  89324. var currentSnapDragDistance = 0;
  89325. _this._dragBehavior.onDragObservable.add(function (event) {
  89326. if (_this.attachedMesh && lastDragPosition) {
  89327. if (!_this.attachedMesh.rotationQuaternion) {
  89328. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  89329. }
  89330. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89331. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89332. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89333. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89334. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89335. var angle = Math.atan2(cross.length(), dot);
  89336. planeNormalTowardsCamera.copyFrom(planeNormal);
  89337. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89338. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89339. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89340. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89341. }
  89342. // Flip up vector depending on which side the camera is on
  89343. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89344. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89345. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89346. planeNormalTowardsCamera.scaleInPlace(-1);
  89347. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89348. }
  89349. }
  89350. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89351. if (halfCircleSide)
  89352. angle = -angle;
  89353. // Snapping logic
  89354. var snapped = false;
  89355. if (_this.snapDistance != 0) {
  89356. currentSnapDragDistance += angle;
  89357. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89358. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89359. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89360. angle = _this.snapDistance * dragSteps;
  89361. snapped = true;
  89362. }
  89363. else {
  89364. angle = 0;
  89365. }
  89366. }
  89367. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89368. var quaternionCoefficient = Math.sin(angle / 2);
  89369. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89370. // Rotate selected mesh quaternion over fixed axis
  89371. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89372. lastDragPosition = event.dragPlanePoint;
  89373. if (snapped) {
  89374. tmpSnapEvent.snapDistance = angle;
  89375. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89376. }
  89377. }
  89378. });
  89379. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89380. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89381. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89382. m.material = hoverMaterial;
  89383. });
  89384. }
  89385. else {
  89386. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89387. m.material = coloredMaterial;
  89388. });
  89389. }
  89390. });
  89391. return _this;
  89392. }
  89393. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89394. if (this._dragBehavior) {
  89395. this._dragBehavior.enabled = value ? true : false;
  89396. }
  89397. };
  89398. /**
  89399. * Disposes of the gizmo
  89400. */
  89401. PlaneRotationGizmo.prototype.dispose = function () {
  89402. this.onSnapObservable.clear();
  89403. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89404. this._dragBehavior.detach();
  89405. _super.prototype.dispose.call(this);
  89406. };
  89407. return PlaneRotationGizmo;
  89408. }(BABYLON.Gizmo));
  89409. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89410. })(BABYLON || (BABYLON = {}));
  89411. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89412. var BABYLON;
  89413. (function (BABYLON) {
  89414. /**
  89415. * Gizmo that enables dragging a mesh along 3 axis
  89416. */
  89417. var PositionGizmo = /** @class */ (function (_super) {
  89418. __extends(PositionGizmo, _super);
  89419. /**
  89420. * Creates a PositionGizmo
  89421. * @param gizmoLayer The utility layer the gizmo will be added to
  89422. */
  89423. function PositionGizmo(gizmoLayer) {
  89424. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89425. var _this = _super.call(this, gizmoLayer) || this;
  89426. _this._xDrag = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89427. _this._yDrag = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89428. _this._zDrag = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89429. _this.attachedMesh = null;
  89430. return _this;
  89431. }
  89432. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89433. set: function (mesh) {
  89434. if (this._xDrag) {
  89435. this._xDrag.attachedMesh = mesh;
  89436. this._yDrag.attachedMesh = mesh;
  89437. this._zDrag.attachedMesh = mesh;
  89438. }
  89439. },
  89440. enumerable: true,
  89441. configurable: true
  89442. });
  89443. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89444. get: function () {
  89445. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89446. },
  89447. set: function (value) {
  89448. if (this._xDrag) {
  89449. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89450. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89451. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89452. }
  89453. },
  89454. enumerable: true,
  89455. configurable: true
  89456. });
  89457. /**
  89458. * Disposes of the gizmo
  89459. */
  89460. PositionGizmo.prototype.dispose = function () {
  89461. this._xDrag.dispose();
  89462. this._yDrag.dispose();
  89463. this._zDrag.dispose();
  89464. };
  89465. return PositionGizmo;
  89466. }(BABYLON.Gizmo));
  89467. BABYLON.PositionGizmo = PositionGizmo;
  89468. })(BABYLON || (BABYLON = {}));
  89469. //# sourceMappingURL=babylon.positionGizmo.js.map
  89470. var BABYLON;
  89471. (function (BABYLON) {
  89472. /**
  89473. * Gizmo that enables rotating a mesh along 3 axis
  89474. */
  89475. var RotationGizmo = /** @class */ (function (_super) {
  89476. __extends(RotationGizmo, _super);
  89477. /**
  89478. * Creates a RotationGizmo
  89479. * @param gizmoLayer The utility layer the gizmo will be added to
  89480. */
  89481. function RotationGizmo(gizmoLayer) {
  89482. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89483. var _this = _super.call(this, gizmoLayer) || this;
  89484. _this._xDrag = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89485. _this._yDrag = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89486. _this._zDrag = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89487. _this.attachedMesh = null;
  89488. return _this;
  89489. }
  89490. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89491. set: function (mesh) {
  89492. if (this._xDrag) {
  89493. this._xDrag.attachedMesh = mesh;
  89494. this._yDrag.attachedMesh = mesh;
  89495. this._zDrag.attachedMesh = mesh;
  89496. }
  89497. },
  89498. enumerable: true,
  89499. configurable: true
  89500. });
  89501. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89502. get: function () {
  89503. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89504. },
  89505. set: function (value) {
  89506. if (this._xDrag) {
  89507. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89508. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89509. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89510. }
  89511. },
  89512. enumerable: true,
  89513. configurable: true
  89514. });
  89515. /**
  89516. * Disposes of the gizmo
  89517. */
  89518. RotationGizmo.prototype.dispose = function () {
  89519. this._xDrag.dispose();
  89520. this._yDrag.dispose();
  89521. this._zDrag.dispose();
  89522. };
  89523. return RotationGizmo;
  89524. }(BABYLON.Gizmo));
  89525. BABYLON.RotationGizmo = RotationGizmo;
  89526. })(BABYLON || (BABYLON = {}));
  89527. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89528. var BABYLON;
  89529. (function (BABYLON) {
  89530. /**
  89531. * Gizmo that enables scaling a mesh along 3 axis
  89532. */
  89533. var ScaleGizmo = /** @class */ (function (_super) {
  89534. __extends(ScaleGizmo, _super);
  89535. /**
  89536. * Creates a ScaleGizmo
  89537. * @param gizmoLayer The utility layer the gizmo will be added to
  89538. */
  89539. function ScaleGizmo(gizmoLayer) {
  89540. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89541. var _this = _super.call(this, gizmoLayer) || this;
  89542. _this._xDrag = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89543. _this._yDrag = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89544. _this._zDrag = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89545. _this.attachedMesh = null;
  89546. return _this;
  89547. }
  89548. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89549. set: function (mesh) {
  89550. if (this._xDrag) {
  89551. this._xDrag.attachedMesh = mesh;
  89552. this._yDrag.attachedMesh = mesh;
  89553. this._zDrag.attachedMesh = mesh;
  89554. }
  89555. },
  89556. enumerable: true,
  89557. configurable: true
  89558. });
  89559. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89560. get: function () {
  89561. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89562. },
  89563. set: function (value) {
  89564. if (this._xDrag) {
  89565. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89566. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89567. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89568. }
  89569. },
  89570. enumerable: true,
  89571. configurable: true
  89572. });
  89573. /**
  89574. * Disposes of the gizmo
  89575. */
  89576. ScaleGizmo.prototype.dispose = function () {
  89577. this._xDrag.dispose();
  89578. this._yDrag.dispose();
  89579. this._zDrag.dispose();
  89580. };
  89581. return ScaleGizmo;
  89582. }(BABYLON.Gizmo));
  89583. BABYLON.ScaleGizmo = ScaleGizmo;
  89584. })(BABYLON || (BABYLON = {}));
  89585. //# sourceMappingURL=babylon.scaleGizmo.js.map
  89586. var BABYLON;
  89587. (function (BABYLON) {
  89588. /**
  89589. * Bounding box gizmo
  89590. */
  89591. var BoundingBoxGizmo = /** @class */ (function (_super) {
  89592. __extends(BoundingBoxGizmo, _super);
  89593. /**
  89594. * Creates an BoundingBoxGizmo
  89595. * @param gizmoLayer The utility layer the gizmo will be added to
  89596. * @param color The color of the gizmo
  89597. */
  89598. function BoundingBoxGizmo(color, gizmoLayer) {
  89599. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89600. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89601. var _this = _super.call(this, gizmoLayer) || this;
  89602. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  89603. _this._renderObserver = null;
  89604. _this._pointerObserver = null;
  89605. _this._scaleDragSpeed = 0.2;
  89606. _this._tmpQuaternion = new BABYLON.Quaternion();
  89607. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89608. /**
  89609. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  89610. */
  89611. _this.rotationSphereSize = 0.1;
  89612. /**
  89613. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  89614. */
  89615. _this.scaleBoxSize = 0.1;
  89616. /**
  89617. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  89618. */
  89619. _this.fixedDragMeshScreenSize = false;
  89620. /**
  89621. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  89622. */
  89623. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  89624. /**
  89625. * Fired when a rotation sphere or scale box is dragged
  89626. */
  89627. _this.onDragStartObservable = new BABYLON.Observable();
  89628. /**
  89629. * Fired when a rotation sphere or scale box drag is started
  89630. */
  89631. _this.onDragObservable = new BABYLON.Observable();
  89632. /**
  89633. * Fired when a rotation sphere or scale box drag is needed
  89634. */
  89635. _this.onDragEndObservable = new BABYLON.Observable();
  89636. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  89637. _this._updateScale = false;
  89638. // Create Materials
  89639. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89640. coloredMaterial.disableLighting = true;
  89641. coloredMaterial.emissiveColor = color;
  89642. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89643. hoverColoredMaterial.disableLighting = true;
  89644. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89645. // Build bounding box out of lines
  89646. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89647. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  89648. var lines = [];
  89649. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  89650. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89651. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89652. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89653. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89654. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89655. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89656. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89657. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89658. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89659. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89660. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89661. lines.forEach(function (l) {
  89662. l.color = color;
  89663. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  89664. l.isPickable = false;
  89665. _this._lineBoundingBox.addChild(l);
  89666. });
  89667. _this._rootMesh.addChild(_this._lineBoundingBox);
  89668. // Create rotation spheres
  89669. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89670. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  89671. var _loop_1 = function (i_1) {
  89672. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  89673. sphere.rotationQuaternion = new BABYLON.Quaternion();
  89674. sphere.material = coloredMaterial;
  89675. // Drag behavior
  89676. _dragBehavior = new BABYLON.PointerDragBehavior({});
  89677. _dragBehavior.moveAttached = false;
  89678. _dragBehavior.updateDragPlane = false;
  89679. sphere.addBehavior(_dragBehavior);
  89680. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  89681. var totalTurnAmountOfDrag = 0;
  89682. _dragBehavior.onDragStartObservable.add(function (event) {
  89683. startingTurnDirection.copyFrom(sphere.forward);
  89684. totalTurnAmountOfDrag = 0;
  89685. });
  89686. _dragBehavior.onDragObservable.add(function (event) {
  89687. _this.onDragObservable.notifyObservers({});
  89688. if (_this.attachedMesh) {
  89689. var worldDragDirection = startingTurnDirection;
  89690. // Project the world right on to the drag plane
  89691. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  89692. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  89693. // project drag delta on to the resulting drag axis and rotate based on that
  89694. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  89695. // Rotate based on axis
  89696. if (!_this.attachedMesh.rotationQuaternion) {
  89697. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89698. }
  89699. // Do not allow the object to turn more than a full circle
  89700. totalTurnAmountOfDrag += projectDist;
  89701. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  89702. if (i_1 >= 8) {
  89703. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  89704. }
  89705. else if (i_1 >= 4) {
  89706. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  89707. }
  89708. else {
  89709. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  89710. }
  89711. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  89712. }
  89713. }
  89714. });
  89715. // Selection/deselection
  89716. _dragBehavior.onDragStartObservable.add(function () {
  89717. _this.onDragStartObservable.notifyObservers({});
  89718. _this._selectNode(sphere);
  89719. });
  89720. _dragBehavior.onDragEndObservable.add(function () {
  89721. _this.onDragEndObservable.notifyObservers({});
  89722. _this._selectNode(null);
  89723. });
  89724. this_1._rotateSpheresParent.addChild(sphere);
  89725. };
  89726. var this_1 = this, _dragBehavior;
  89727. for (var i_1 = 0; i_1 < 12; i_1++) {
  89728. _loop_1(i_1);
  89729. }
  89730. _this._rootMesh.addChild(_this._rotateSpheresParent);
  89731. // Create scale cubes
  89732. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89733. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  89734. for (var i = 0; i < 2; i++) {
  89735. for (var j = 0; j < 2; j++) {
  89736. var _loop_2 = function () {
  89737. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  89738. box.material = coloredMaterial;
  89739. // Dragging logic
  89740. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  89741. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89742. _dragBehavior.moveAttached = false;
  89743. box.addBehavior(_dragBehavior);
  89744. _dragBehavior.onDragObservable.add(function (event) {
  89745. _this.onDragObservable.notifyObservers({});
  89746. if (_this.attachedMesh) {
  89747. // Current boudning box dimensions
  89748. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  89749. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  89750. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  89751. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  89752. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  89753. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  89754. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  89755. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  89756. // Update scale and position
  89757. _this.attachedMesh.scaling.addInPlace(deltaScale);
  89758. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  89759. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  89760. }
  89761. });
  89762. // Selection/deselection
  89763. _dragBehavior.onDragStartObservable.add(function () {
  89764. _this.onDragStartObservable.notifyObservers({});
  89765. _this._selectNode(box);
  89766. });
  89767. _dragBehavior.onDragEndObservable.add(function () {
  89768. _this.onDragEndObservable.notifyObservers({});
  89769. _this._selectNode(null);
  89770. });
  89771. this_2._scaleBoxesParent.addChild(box);
  89772. };
  89773. var this_2 = this, _dragBehavior;
  89774. for (var k = 0; k < 2; k++) {
  89775. _loop_2();
  89776. }
  89777. }
  89778. }
  89779. _this._rootMesh.addChild(_this._scaleBoxesParent);
  89780. // Hover color change
  89781. var pointerIds = new Array();
  89782. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89783. if (!pointerIds[pointerInfo.event.pointerId]) {
  89784. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  89785. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  89786. pointerIds[pointerInfo.event.pointerId] = mesh;
  89787. mesh.material = hoverColoredMaterial;
  89788. }
  89789. });
  89790. }
  89791. else {
  89792. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  89793. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  89794. delete pointerIds[pointerInfo.event.pointerId];
  89795. }
  89796. }
  89797. });
  89798. // Update bounding box positions
  89799. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  89800. _this._updateBoundingBox();
  89801. });
  89802. _this._updateBoundingBox();
  89803. return _this;
  89804. }
  89805. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  89806. this._rotateSpheresParent.getChildMeshes()
  89807. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  89808. m.isVisible = (!selectedMesh || m == selectedMesh);
  89809. });
  89810. };
  89811. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  89812. if (this.attachedMesh) {
  89813. // Update bounding dimensions/positions
  89814. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  89815. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  89816. this._boundingDimensions.copyFrom(boundBoxDimensions);
  89817. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  89818. }
  89819. // Update rotation sphere locations
  89820. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  89821. for (var i = 0; i < 3; i++) {
  89822. for (var j = 0; j < 2; j++) {
  89823. for (var k = 0; k < 2; k++) {
  89824. var index = ((i * 4) + (j * 2)) + k;
  89825. if (i == 0) {
  89826. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89827. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89828. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89829. }
  89830. if (i == 1) {
  89831. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  89832. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89833. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89834. }
  89835. if (i == 2) {
  89836. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  89837. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89838. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89839. }
  89840. if (this.fixedDragMeshScreenSize) {
  89841. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  89842. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  89843. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  89844. }
  89845. else {
  89846. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  89847. }
  89848. }
  89849. }
  89850. }
  89851. // Update scale box locations
  89852. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  89853. for (var i = 0; i < 2; i++) {
  89854. for (var j = 0; j < 2; j++) {
  89855. for (var k = 0; k < 2; k++) {
  89856. var index = ((i * 4) + (j * 2)) + k;
  89857. if (scaleBoxes[index]) {
  89858. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89859. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89860. if (this.fixedDragMeshScreenSize) {
  89861. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  89862. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  89863. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  89864. }
  89865. else {
  89866. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  89867. }
  89868. }
  89869. }
  89870. }
  89871. }
  89872. };
  89873. /**
  89874. * Enables rotation on the specified axis and disables rotation on the others
  89875. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  89876. */
  89877. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  89878. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  89879. if (i < 4) {
  89880. m.setEnabled(axis.indexOf("x") != -1);
  89881. }
  89882. else if (i < 8) {
  89883. m.setEnabled(axis.indexOf("y") != -1);
  89884. }
  89885. else {
  89886. m.setEnabled(axis.indexOf("z") != -1);
  89887. }
  89888. });
  89889. };
  89890. /**
  89891. * Disposes of the gizmo
  89892. */
  89893. BoundingBoxGizmo.prototype.dispose = function () {
  89894. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89895. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  89896. this._lineBoundingBox.dispose();
  89897. this._rotateSpheresParent.dispose();
  89898. this._scaleBoxesParent.dispose();
  89899. _super.prototype.dispose.call(this);
  89900. };
  89901. return BoundingBoxGizmo;
  89902. }(BABYLON.Gizmo));
  89903. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  89904. })(BABYLON || (BABYLON = {}));
  89905. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  89906. var BABYLON;
  89907. (function (BABYLON) {
  89908. /**
  89909. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  89910. */
  89911. var GizmoManager = /** @class */ (function () {
  89912. /**
  89913. * Instatiates a gizmo manager
  89914. * @param scene the scene to overlay the gizmos on top of
  89915. * @param options If only a single gizmo should exist at one time
  89916. */
  89917. function GizmoManager(scene, options) {
  89918. var _this = this;
  89919. this.scene = scene;
  89920. // Set of gizmos that are currently in the scene for each mesh
  89921. this._gizmoSet = {};
  89922. this._pointerObserver = null;
  89923. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  89924. // Options parsing
  89925. if (!options) {
  89926. options = {};
  89927. }
  89928. if (options.singleGizmo === undefined) {
  89929. options.singleGizmo = true;
  89930. }
  89931. // Instatiate/dispose gizmos based on pointer actions
  89932. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  89933. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89934. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  89935. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  89936. if (options.singleGizmo) {
  89937. _this._clearGizmos();
  89938. }
  89939. // Enable gizmo when mesh is selected
  89940. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  89941. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89942. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89943. }
  89944. else {
  89945. if (!options.singleGizmo) {
  89946. // Disable gizmo when clicked again
  89947. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  89948. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  89949. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  89950. }
  89951. }
  89952. }
  89953. else {
  89954. if (options.singleGizmo) {
  89955. // Disable gizmo when clicked away
  89956. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89957. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  89958. if (gizmoPick && !gizmoPick.hit) {
  89959. _this._clearGizmos();
  89960. }
  89961. }
  89962. }
  89963. }
  89964. }
  89965. });
  89966. }
  89967. /**
  89968. * Disposes of the gizmo manager
  89969. */
  89970. GizmoManager.prototype.dispose = function () {
  89971. this.scene.onPointerObservable.remove(this._pointerObserver);
  89972. this._clearGizmos();
  89973. this._gizmoLayer.dispose();
  89974. };
  89975. GizmoManager.prototype._clearGizmos = function () {
  89976. for (var key in this._gizmoSet) {
  89977. if (this._gizmoSet.hasOwnProperty(key)) {
  89978. this._gizmoSet[key].positionGizmo.dispose();
  89979. this._gizmoSet[key].rotationGizmo.dispose();
  89980. delete this._gizmoSet[key];
  89981. }
  89982. }
  89983. };
  89984. return GizmoManager;
  89985. }());
  89986. BABYLON.GizmoManager = GizmoManager;
  89987. })(BABYLON || (BABYLON = {}));
  89988. //# sourceMappingURL=babylon.gizmoManager.js.map
  89989. var BABYLON;
  89990. (function (BABYLON) {
  89991. /**
  89992. * Defines a target to use with MorphTargetManager
  89993. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89994. */
  89995. var MorphTarget = /** @class */ (function () {
  89996. /**
  89997. * Creates a new MorphTarget
  89998. * @param name defines the name of the target
  89999. * @param influence defines the influence to use
  90000. */
  90001. function MorphTarget(
  90002. /** defines the name of the target */
  90003. name, influence, scene) {
  90004. if (influence === void 0) { influence = 0; }
  90005. if (scene === void 0) { scene = null; }
  90006. this.name = name;
  90007. /**
  90008. * Gets or sets the list of animations
  90009. */
  90010. this.animations = new Array();
  90011. this._positions = null;
  90012. this._normals = null;
  90013. this._tangents = null;
  90014. /**
  90015. * Observable raised when the influence changes
  90016. */
  90017. this.onInfluenceChanged = new BABYLON.Observable();
  90018. this._animationPropertiesOverride = null;
  90019. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90020. this.influence = influence;
  90021. }
  90022. Object.defineProperty(MorphTarget.prototype, "influence", {
  90023. /**
  90024. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90025. */
  90026. get: function () {
  90027. return this._influence;
  90028. },
  90029. set: function (influence) {
  90030. if (this._influence === influence) {
  90031. return;
  90032. }
  90033. var previous = this._influence;
  90034. this._influence = influence;
  90035. if (this.onInfluenceChanged.hasObservers) {
  90036. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90037. }
  90038. },
  90039. enumerable: true,
  90040. configurable: true
  90041. });
  90042. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90043. /**
  90044. * Gets or sets the animation properties override
  90045. */
  90046. get: function () {
  90047. if (!this._animationPropertiesOverride && this._scene) {
  90048. return this._scene.animationPropertiesOverride;
  90049. }
  90050. return this._animationPropertiesOverride;
  90051. },
  90052. set: function (value) {
  90053. this._animationPropertiesOverride = value;
  90054. },
  90055. enumerable: true,
  90056. configurable: true
  90057. });
  90058. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90059. /**
  90060. * Gets a boolean defining if the target contains position data
  90061. */
  90062. get: function () {
  90063. return !!this._positions;
  90064. },
  90065. enumerable: true,
  90066. configurable: true
  90067. });
  90068. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90069. /**
  90070. * Gets a boolean defining if the target contains normal data
  90071. */
  90072. get: function () {
  90073. return !!this._normals;
  90074. },
  90075. enumerable: true,
  90076. configurable: true
  90077. });
  90078. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90079. /**
  90080. * Gets a boolean defining if the target contains tangent data
  90081. */
  90082. get: function () {
  90083. return !!this._tangents;
  90084. },
  90085. enumerable: true,
  90086. configurable: true
  90087. });
  90088. /**
  90089. * Affects position data to this target
  90090. * @param data defines the position data to use
  90091. */
  90092. MorphTarget.prototype.setPositions = function (data) {
  90093. this._positions = data;
  90094. };
  90095. /**
  90096. * Gets the position data stored in this target
  90097. * @returns a FloatArray containing the position data (or null if not present)
  90098. */
  90099. MorphTarget.prototype.getPositions = function () {
  90100. return this._positions;
  90101. };
  90102. /**
  90103. * Affects normal data to this target
  90104. * @param data defines the normal data to use
  90105. */
  90106. MorphTarget.prototype.setNormals = function (data) {
  90107. this._normals = data;
  90108. };
  90109. /**
  90110. * Gets the normal data stored in this target
  90111. * @returns a FloatArray containing the normal data (or null if not present)
  90112. */
  90113. MorphTarget.prototype.getNormals = function () {
  90114. return this._normals;
  90115. };
  90116. /**
  90117. * Affects tangent data to this target
  90118. * @param data defines the tangent data to use
  90119. */
  90120. MorphTarget.prototype.setTangents = function (data) {
  90121. this._tangents = data;
  90122. };
  90123. /**
  90124. * Gets the tangent data stored in this target
  90125. * @returns a FloatArray containing the tangent data (or null if not present)
  90126. */
  90127. MorphTarget.prototype.getTangents = function () {
  90128. return this._tangents;
  90129. };
  90130. /**
  90131. * Serializes the current target into a Serialization object
  90132. * @returns the serialized object
  90133. */
  90134. MorphTarget.prototype.serialize = function () {
  90135. var serializationObject = {};
  90136. serializationObject.name = this.name;
  90137. serializationObject.influence = this.influence;
  90138. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90139. if (this.hasNormals) {
  90140. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90141. }
  90142. if (this.hasTangents) {
  90143. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90144. }
  90145. // Animations
  90146. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90147. return serializationObject;
  90148. };
  90149. // Statics
  90150. /**
  90151. * Creates a new target from serialized data
  90152. * @param serializationObject defines the serialized data to use
  90153. * @returns a new MorphTarget
  90154. */
  90155. MorphTarget.Parse = function (serializationObject) {
  90156. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90157. result.setPositions(serializationObject.positions);
  90158. if (serializationObject.normals) {
  90159. result.setNormals(serializationObject.normals);
  90160. }
  90161. if (serializationObject.tangents) {
  90162. result.setTangents(serializationObject.tangents);
  90163. }
  90164. // Animations
  90165. if (serializationObject.animations) {
  90166. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90167. var parsedAnimation = serializationObject.animations[animationIndex];
  90168. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90169. }
  90170. }
  90171. return result;
  90172. };
  90173. /**
  90174. * Creates a MorphTarget from mesh data
  90175. * @param mesh defines the source mesh
  90176. * @param name defines the name to use for the new target
  90177. * @param influence defines the influence to attach to the target
  90178. * @returns a new MorphTarget
  90179. */
  90180. MorphTarget.FromMesh = function (mesh, name, influence) {
  90181. if (!name) {
  90182. name = mesh.name;
  90183. }
  90184. var result = new MorphTarget(name, influence, mesh.getScene());
  90185. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90186. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90187. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90188. }
  90189. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90190. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90191. }
  90192. return result;
  90193. };
  90194. return MorphTarget;
  90195. }());
  90196. BABYLON.MorphTarget = MorphTarget;
  90197. })(BABYLON || (BABYLON = {}));
  90198. //# sourceMappingURL=babylon.morphTarget.js.map
  90199. var BABYLON;
  90200. (function (BABYLON) {
  90201. /**
  90202. * This class is used to deform meshes using morphing between different targets
  90203. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90204. */
  90205. var MorphTargetManager = /** @class */ (function () {
  90206. /**
  90207. * Creates a new MorphTargetManager
  90208. * @param scene defines the current scene
  90209. */
  90210. function MorphTargetManager(scene) {
  90211. if (scene === void 0) { scene = null; }
  90212. this._targets = new Array();
  90213. this._targetObservable = new Array();
  90214. this._activeTargets = new BABYLON.SmartArray(16);
  90215. this._supportsNormals = false;
  90216. this._supportsTangents = false;
  90217. this._vertexCount = 0;
  90218. this._uniqueId = 0;
  90219. this._tempInfluences = new Array();
  90220. if (!scene) {
  90221. scene = BABYLON.Engine.LastCreatedScene;
  90222. }
  90223. this._scene = scene;
  90224. if (this._scene) {
  90225. this._scene.morphTargetManagers.push(this);
  90226. this._uniqueId = this._scene.getUniqueId();
  90227. }
  90228. }
  90229. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90230. /**
  90231. * Gets the unique ID of this manager
  90232. */
  90233. get: function () {
  90234. return this._uniqueId;
  90235. },
  90236. enumerable: true,
  90237. configurable: true
  90238. });
  90239. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90240. /**
  90241. * Gets the number of vertices handled by this manager
  90242. */
  90243. get: function () {
  90244. return this._vertexCount;
  90245. },
  90246. enumerable: true,
  90247. configurable: true
  90248. });
  90249. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90250. /**
  90251. * Gets a boolean indicating if this manager supports morphing of normals
  90252. */
  90253. get: function () {
  90254. return this._supportsNormals;
  90255. },
  90256. enumerable: true,
  90257. configurable: true
  90258. });
  90259. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90260. /**
  90261. * Gets a boolean indicating if this manager supports morphing of tangents
  90262. */
  90263. get: function () {
  90264. return this._supportsTangents;
  90265. },
  90266. enumerable: true,
  90267. configurable: true
  90268. });
  90269. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90270. /**
  90271. * Gets the number of targets stored in this manager
  90272. */
  90273. get: function () {
  90274. return this._targets.length;
  90275. },
  90276. enumerable: true,
  90277. configurable: true
  90278. });
  90279. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90280. /**
  90281. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90282. */
  90283. get: function () {
  90284. return this._activeTargets.length;
  90285. },
  90286. enumerable: true,
  90287. configurable: true
  90288. });
  90289. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90290. /**
  90291. * Gets the list of influences (one per target)
  90292. */
  90293. get: function () {
  90294. return this._influences;
  90295. },
  90296. enumerable: true,
  90297. configurable: true
  90298. });
  90299. /**
  90300. * Gets the active target at specified index. An active target is a target with an influence > 0
  90301. * @param index defines the index to check
  90302. * @returns the requested target
  90303. */
  90304. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90305. return this._activeTargets.data[index];
  90306. };
  90307. /**
  90308. * Gets the target at specified index
  90309. * @param index defines the index to check
  90310. * @returns the requested target
  90311. */
  90312. MorphTargetManager.prototype.getTarget = function (index) {
  90313. return this._targets[index];
  90314. };
  90315. /**
  90316. * Add a new target to this manager
  90317. * @param target defines the target to add
  90318. */
  90319. MorphTargetManager.prototype.addTarget = function (target) {
  90320. var _this = this;
  90321. this._targets.push(target);
  90322. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90323. _this._syncActiveTargets(needUpdate);
  90324. }));
  90325. this._syncActiveTargets(true);
  90326. };
  90327. /**
  90328. * Removes a target from the manager
  90329. * @param target defines the target to remove
  90330. */
  90331. MorphTargetManager.prototype.removeTarget = function (target) {
  90332. var index = this._targets.indexOf(target);
  90333. if (index >= 0) {
  90334. this._targets.splice(index, 1);
  90335. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90336. this._syncActiveTargets(true);
  90337. }
  90338. };
  90339. /**
  90340. * Serializes the current manager into a Serialization object
  90341. * @returns the serialized object
  90342. */
  90343. MorphTargetManager.prototype.serialize = function () {
  90344. var serializationObject = {};
  90345. serializationObject.id = this.uniqueId;
  90346. serializationObject.targets = [];
  90347. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90348. var target = _a[_i];
  90349. serializationObject.targets.push(target.serialize());
  90350. }
  90351. return serializationObject;
  90352. };
  90353. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90354. var influenceCount = 0;
  90355. this._activeTargets.reset();
  90356. this._supportsNormals = true;
  90357. this._supportsTangents = true;
  90358. this._vertexCount = 0;
  90359. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90360. var target = _a[_i];
  90361. this._activeTargets.push(target);
  90362. this._tempInfluences[influenceCount++] = target.influence;
  90363. var positions = target.getPositions();
  90364. if (positions) {
  90365. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90366. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90367. var vertexCount = positions.length / 3;
  90368. if (this._vertexCount === 0) {
  90369. this._vertexCount = vertexCount;
  90370. }
  90371. else if (this._vertexCount !== vertexCount) {
  90372. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90373. return;
  90374. }
  90375. }
  90376. }
  90377. if (!this._influences || this._influences.length !== influenceCount) {
  90378. this._influences = new Float32Array(influenceCount);
  90379. }
  90380. for (var index = 0; index < influenceCount; index++) {
  90381. this._influences[index] = this._tempInfluences[index];
  90382. }
  90383. if (needUpdate) {
  90384. this.synchronize();
  90385. }
  90386. };
  90387. /**
  90388. * Syncrhonize the targets with all the meshes using this morph target manager
  90389. */
  90390. MorphTargetManager.prototype.synchronize = function () {
  90391. if (!this._scene) {
  90392. return;
  90393. }
  90394. // Flag meshes as dirty to resync with the active targets
  90395. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90396. var mesh = _a[_i];
  90397. if (mesh.morphTargetManager === this) {
  90398. mesh._syncGeometryWithMorphTargetManager();
  90399. }
  90400. }
  90401. };
  90402. // Statics
  90403. /**
  90404. * Creates a new MorphTargetManager from serialized data
  90405. * @param serializationObject defines the serialized data
  90406. * @param scene defines the hosting scene
  90407. * @returns the new MorphTargetManager
  90408. */
  90409. MorphTargetManager.Parse = function (serializationObject, scene) {
  90410. var result = new MorphTargetManager(scene);
  90411. result._uniqueId = serializationObject.id;
  90412. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90413. var targetData = _a[_i];
  90414. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90415. }
  90416. return result;
  90417. };
  90418. return MorphTargetManager;
  90419. }());
  90420. BABYLON.MorphTargetManager = MorphTargetManager;
  90421. })(BABYLON || (BABYLON = {}));
  90422. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90423. var BABYLON;
  90424. (function (BABYLON) {
  90425. var Octree = /** @class */ (function () {
  90426. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90427. if (maxDepth === void 0) { maxDepth = 2; }
  90428. this.maxDepth = maxDepth;
  90429. this.dynamicContent = new Array();
  90430. this._maxBlockCapacity = maxBlockCapacity || 64;
  90431. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90432. this._creationFunc = creationFunc;
  90433. }
  90434. // Methods
  90435. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90436. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90437. };
  90438. Octree.prototype.addMesh = function (entry) {
  90439. for (var index = 0; index < this.blocks.length; index++) {
  90440. var block = this.blocks[index];
  90441. block.addEntry(entry);
  90442. }
  90443. };
  90444. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90445. this._selectionContent.reset();
  90446. for (var index = 0; index < this.blocks.length; index++) {
  90447. var block = this.blocks[index];
  90448. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90449. }
  90450. if (allowDuplicate) {
  90451. this._selectionContent.concat(this.dynamicContent);
  90452. }
  90453. else {
  90454. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90455. }
  90456. return this._selectionContent;
  90457. };
  90458. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90459. this._selectionContent.reset();
  90460. for (var index = 0; index < this.blocks.length; index++) {
  90461. var block = this.blocks[index];
  90462. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  90463. }
  90464. if (allowDuplicate) {
  90465. this._selectionContent.concat(this.dynamicContent);
  90466. }
  90467. else {
  90468. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90469. }
  90470. return this._selectionContent;
  90471. };
  90472. Octree.prototype.intersectsRay = function (ray) {
  90473. this._selectionContent.reset();
  90474. for (var index = 0; index < this.blocks.length; index++) {
  90475. var block = this.blocks[index];
  90476. block.intersectsRay(ray, this._selectionContent);
  90477. }
  90478. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90479. return this._selectionContent;
  90480. };
  90481. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  90482. target.blocks = new Array();
  90483. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  90484. // Segmenting space
  90485. for (var x = 0; x < 2; x++) {
  90486. for (var y = 0; y < 2; y++) {
  90487. for (var z = 0; z < 2; z++) {
  90488. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  90489. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  90490. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  90491. block.addEntries(entries);
  90492. target.blocks.push(block);
  90493. }
  90494. }
  90495. }
  90496. };
  90497. Octree.CreationFuncForMeshes = function (entry, block) {
  90498. var boundingInfo = entry.getBoundingInfo();
  90499. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90500. block.entries.push(entry);
  90501. }
  90502. };
  90503. Octree.CreationFuncForSubMeshes = function (entry, block) {
  90504. var boundingInfo = entry.getBoundingInfo();
  90505. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90506. block.entries.push(entry);
  90507. }
  90508. };
  90509. return Octree;
  90510. }());
  90511. BABYLON.Octree = Octree;
  90512. })(BABYLON || (BABYLON = {}));
  90513. //# sourceMappingURL=babylon.octree.js.map
  90514. var BABYLON;
  90515. (function (BABYLON) {
  90516. var OctreeBlock = /** @class */ (function () {
  90517. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  90518. this.entries = new Array();
  90519. this._boundingVectors = new Array();
  90520. this._capacity = capacity;
  90521. this._depth = depth;
  90522. this._maxDepth = maxDepth;
  90523. this._creationFunc = creationFunc;
  90524. this._minPoint = minPoint;
  90525. this._maxPoint = maxPoint;
  90526. this._boundingVectors.push(minPoint.clone());
  90527. this._boundingVectors.push(maxPoint.clone());
  90528. this._boundingVectors.push(minPoint.clone());
  90529. this._boundingVectors[2].x = maxPoint.x;
  90530. this._boundingVectors.push(minPoint.clone());
  90531. this._boundingVectors[3].y = maxPoint.y;
  90532. this._boundingVectors.push(minPoint.clone());
  90533. this._boundingVectors[4].z = maxPoint.z;
  90534. this._boundingVectors.push(maxPoint.clone());
  90535. this._boundingVectors[5].z = minPoint.z;
  90536. this._boundingVectors.push(maxPoint.clone());
  90537. this._boundingVectors[6].x = minPoint.x;
  90538. this._boundingVectors.push(maxPoint.clone());
  90539. this._boundingVectors[7].y = minPoint.y;
  90540. }
  90541. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  90542. // Property
  90543. get: function () {
  90544. return this._capacity;
  90545. },
  90546. enumerable: true,
  90547. configurable: true
  90548. });
  90549. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  90550. get: function () {
  90551. return this._minPoint;
  90552. },
  90553. enumerable: true,
  90554. configurable: true
  90555. });
  90556. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  90557. get: function () {
  90558. return this._maxPoint;
  90559. },
  90560. enumerable: true,
  90561. configurable: true
  90562. });
  90563. // Methods
  90564. OctreeBlock.prototype.addEntry = function (entry) {
  90565. if (this.blocks) {
  90566. for (var index = 0; index < this.blocks.length; index++) {
  90567. var block = this.blocks[index];
  90568. block.addEntry(entry);
  90569. }
  90570. return;
  90571. }
  90572. this._creationFunc(entry, this);
  90573. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  90574. this.createInnerBlocks();
  90575. }
  90576. };
  90577. OctreeBlock.prototype.addEntries = function (entries) {
  90578. for (var index = 0; index < entries.length; index++) {
  90579. var mesh = entries[index];
  90580. this.addEntry(mesh);
  90581. }
  90582. };
  90583. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  90584. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  90585. if (this.blocks) {
  90586. for (var index = 0; index < this.blocks.length; index++) {
  90587. var block = this.blocks[index];
  90588. block.select(frustumPlanes, selection, allowDuplicate);
  90589. }
  90590. return;
  90591. }
  90592. if (allowDuplicate) {
  90593. selection.concat(this.entries);
  90594. }
  90595. else {
  90596. selection.concatWithNoDuplicate(this.entries);
  90597. }
  90598. }
  90599. };
  90600. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  90601. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  90602. if (this.blocks) {
  90603. for (var index = 0; index < this.blocks.length; index++) {
  90604. var block = this.blocks[index];
  90605. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  90606. }
  90607. return;
  90608. }
  90609. if (allowDuplicate) {
  90610. selection.concat(this.entries);
  90611. }
  90612. else {
  90613. selection.concatWithNoDuplicate(this.entries);
  90614. }
  90615. }
  90616. };
  90617. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  90618. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  90619. if (this.blocks) {
  90620. for (var index = 0; index < this.blocks.length; index++) {
  90621. var block = this.blocks[index];
  90622. block.intersectsRay(ray, selection);
  90623. }
  90624. return;
  90625. }
  90626. selection.concatWithNoDuplicate(this.entries);
  90627. }
  90628. };
  90629. OctreeBlock.prototype.createInnerBlocks = function () {
  90630. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  90631. };
  90632. return OctreeBlock;
  90633. }());
  90634. BABYLON.OctreeBlock = OctreeBlock;
  90635. })(BABYLON || (BABYLON = {}));
  90636. //# sourceMappingURL=babylon.octreeBlock.js.map
  90637. var BABYLON;
  90638. (function (BABYLON) {
  90639. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  90640. __extends(VRDistortionCorrectionPostProcess, _super);
  90641. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  90642. var _this = _super.call(this, name, "vrDistortionCorrection", [
  90643. 'LensCenter',
  90644. 'Scale',
  90645. 'ScaleIn',
  90646. 'HmdWarpParam'
  90647. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  90648. _this._isRightEye = isRightEye;
  90649. _this._distortionFactors = vrMetrics.distortionK;
  90650. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  90651. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  90652. _this.adaptScaleToCurrentViewport = true;
  90653. _this.onSizeChangedObservable.add(function () {
  90654. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  90655. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  90656. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  90657. });
  90658. _this.onApplyObservable.add(function (effect) {
  90659. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  90660. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  90661. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  90662. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  90663. });
  90664. return _this;
  90665. }
  90666. return VRDistortionCorrectionPostProcess;
  90667. }(BABYLON.PostProcess));
  90668. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  90669. })(BABYLON || (BABYLON = {}));
  90670. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  90671. var BABYLON;
  90672. (function (BABYLON) {
  90673. /**
  90674. * Postprocess used to generate anaglyphic rendering
  90675. */
  90676. var AnaglyphPostProcess = /** @class */ (function (_super) {
  90677. __extends(AnaglyphPostProcess, _super);
  90678. /**
  90679. * Creates a new AnaglyphPostProcess
  90680. * @param name defines postprocess name
  90681. * @param options defines creation options or target ratio scale
  90682. * @param rigCameras defines cameras using this postprocess
  90683. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  90684. * @param engine defines hosting engine
  90685. * @param reusable defines if the postprocess will be reused multiple times per frame
  90686. */
  90687. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  90688. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  90689. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90690. _this.onApplyObservable.add(function (effect) {
  90691. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  90692. });
  90693. return _this;
  90694. }
  90695. return AnaglyphPostProcess;
  90696. }(BABYLON.PostProcess));
  90697. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  90698. })(BABYLON || (BABYLON = {}));
  90699. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  90700. var BABYLON;
  90701. (function (BABYLON) {
  90702. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  90703. __extends(StereoscopicInterlacePostProcess, _super);
  90704. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  90705. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  90706. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90707. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90708. _this.onSizeChangedObservable.add(function () {
  90709. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90710. });
  90711. _this.onApplyObservable.add(function (effect) {
  90712. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  90713. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  90714. });
  90715. return _this;
  90716. }
  90717. return StereoscopicInterlacePostProcess;
  90718. }(BABYLON.PostProcess));
  90719. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  90720. })(BABYLON || (BABYLON = {}));
  90721. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  90722. var BABYLON;
  90723. (function (BABYLON) {
  90724. /**
  90725. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  90726. * Screen rotation is taken into account.
  90727. */
  90728. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  90729. function FreeCameraDeviceOrientationInput() {
  90730. var _this = this;
  90731. this._screenOrientationAngle = 0;
  90732. this._screenQuaternion = new BABYLON.Quaternion();
  90733. this._alpha = 0;
  90734. this._beta = 0;
  90735. this._gamma = 0;
  90736. this._orientationChanged = function () {
  90737. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  90738. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  90739. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  90740. };
  90741. this._deviceOrientation = function (evt) {
  90742. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  90743. _this._beta = evt.beta !== null ? evt.beta : 0;
  90744. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  90745. };
  90746. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  90747. this._orientationChanged();
  90748. }
  90749. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  90750. get: function () {
  90751. return this._camera;
  90752. },
  90753. set: function (camera) {
  90754. this._camera = camera;
  90755. if (this._camera != null && !this._camera.rotationQuaternion) {
  90756. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  90757. }
  90758. },
  90759. enumerable: true,
  90760. configurable: true
  90761. });
  90762. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90763. window.addEventListener("orientationchange", this._orientationChanged);
  90764. window.addEventListener("deviceorientation", this._deviceOrientation);
  90765. //In certain cases, the attach control is called AFTER orientation was changed,
  90766. //So this is needed.
  90767. this._orientationChanged();
  90768. };
  90769. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  90770. window.removeEventListener("orientationchange", this._orientationChanged);
  90771. window.removeEventListener("deviceorientation", this._deviceOrientation);
  90772. };
  90773. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  90774. //if no device orientation provided, don't update the rotation.
  90775. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  90776. if (!this._alpha)
  90777. return;
  90778. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  90779. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  90780. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  90781. //Mirror on XY Plane
  90782. this._camera.rotationQuaternion.z *= -1;
  90783. this._camera.rotationQuaternion.w *= -1;
  90784. };
  90785. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  90786. return "FreeCameraDeviceOrientationInput";
  90787. };
  90788. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  90789. return "deviceOrientation";
  90790. };
  90791. return FreeCameraDeviceOrientationInput;
  90792. }());
  90793. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  90794. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  90795. })(BABYLON || (BABYLON = {}));
  90796. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  90797. var BABYLON;
  90798. (function (BABYLON) {
  90799. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  90800. function ArcRotateCameraVRDeviceOrientationInput() {
  90801. this.alphaCorrection = 1;
  90802. this.betaCorrection = 1;
  90803. this.gammaCorrection = 1;
  90804. this._alpha = 0;
  90805. this._gamma = 0;
  90806. this._dirty = false;
  90807. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  90808. }
  90809. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90810. this.camera.attachControl(element, noPreventDefault);
  90811. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  90812. };
  90813. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  90814. if (evt.alpha !== null) {
  90815. this._alpha = +evt.alpha | 0;
  90816. }
  90817. if (evt.gamma !== null) {
  90818. this._gamma = +evt.gamma | 0;
  90819. }
  90820. this._dirty = true;
  90821. };
  90822. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  90823. if (this._dirty) {
  90824. this._dirty = false;
  90825. if (this._gamma < 0) {
  90826. this._gamma = 180 + this._gamma;
  90827. }
  90828. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  90829. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  90830. }
  90831. };
  90832. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  90833. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  90834. };
  90835. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  90836. return "ArcRotateCameraVRDeviceOrientationInput";
  90837. };
  90838. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  90839. return "VRDeviceOrientation";
  90840. };
  90841. return ArcRotateCameraVRDeviceOrientationInput;
  90842. }());
  90843. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  90844. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  90845. })(BABYLON || (BABYLON = {}));
  90846. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  90847. var BABYLON;
  90848. (function (BABYLON) {
  90849. var VRCameraMetrics = /** @class */ (function () {
  90850. function VRCameraMetrics() {
  90851. this.compensateDistortion = true;
  90852. }
  90853. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  90854. get: function () {
  90855. return this.hResolution / (2 * this.vResolution);
  90856. },
  90857. enumerable: true,
  90858. configurable: true
  90859. });
  90860. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  90861. get: function () {
  90862. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  90863. },
  90864. enumerable: true,
  90865. configurable: true
  90866. });
  90867. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  90868. get: function () {
  90869. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90870. var h = (4 * meters) / this.hScreenSize;
  90871. return BABYLON.Matrix.Translation(h, 0, 0);
  90872. },
  90873. enumerable: true,
  90874. configurable: true
  90875. });
  90876. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  90877. get: function () {
  90878. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90879. var h = (4 * meters) / this.hScreenSize;
  90880. return BABYLON.Matrix.Translation(-h, 0, 0);
  90881. },
  90882. enumerable: true,
  90883. configurable: true
  90884. });
  90885. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  90886. get: function () {
  90887. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  90888. },
  90889. enumerable: true,
  90890. configurable: true
  90891. });
  90892. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  90893. get: function () {
  90894. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  90895. },
  90896. enumerable: true,
  90897. configurable: true
  90898. });
  90899. VRCameraMetrics.GetDefault = function () {
  90900. var result = new VRCameraMetrics();
  90901. result.hResolution = 1280;
  90902. result.vResolution = 800;
  90903. result.hScreenSize = 0.149759993;
  90904. result.vScreenSize = 0.0935999975;
  90905. result.vScreenCenter = 0.0467999987;
  90906. result.eyeToScreenDistance = 0.0410000011;
  90907. result.lensSeparationDistance = 0.0635000020;
  90908. result.interpupillaryDistance = 0.0640000030;
  90909. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  90910. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  90911. result.postProcessScaleFactor = 1.714605507808412;
  90912. result.lensCenterOffset = 0.151976421;
  90913. return result;
  90914. };
  90915. return VRCameraMetrics;
  90916. }());
  90917. BABYLON.VRCameraMetrics = VRCameraMetrics;
  90918. })(BABYLON || (BABYLON = {}));
  90919. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  90920. var BABYLON;
  90921. (function (BABYLON) {
  90922. /**
  90923. * This represents a WebVR camera.
  90924. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  90925. * @example http://doc.babylonjs.com/how_to/webvr_camera
  90926. */
  90927. var WebVRFreeCamera = /** @class */ (function (_super) {
  90928. __extends(WebVRFreeCamera, _super);
  90929. /**
  90930. * Instantiates a WebVRFreeCamera.
  90931. * @param name The name of the WebVRFreeCamera
  90932. * @param position The starting anchor position for the camera
  90933. * @param scene The scene the camera belongs to
  90934. * @param webVROptions a set of customizable options for the webVRCamera
  90935. */
  90936. function WebVRFreeCamera(name, position, scene, webVROptions) {
  90937. if (webVROptions === void 0) { webVROptions = {}; }
  90938. var _this = _super.call(this, name, position, scene) || this;
  90939. _this.webVROptions = webVROptions;
  90940. /**
  90941. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  90942. */
  90943. _this._vrDevice = null;
  90944. /**
  90945. * The rawPose of the vrDevice.
  90946. */
  90947. _this.rawPose = null;
  90948. _this._specsVersion = "1.1";
  90949. _this._attached = false;
  90950. _this._descendants = [];
  90951. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  90952. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  90953. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  90954. _this._standingMatrix = null;
  90955. /**
  90956. * Represents device position in babylon space.
  90957. */
  90958. _this.devicePosition = BABYLON.Vector3.Zero();
  90959. /**
  90960. * Represents device rotation in babylon space.
  90961. */
  90962. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  90963. /**
  90964. * The scale of the device to be used when translating from device space to babylon space.
  90965. */
  90966. _this.deviceScaleFactor = 1;
  90967. _this._deviceToWorld = BABYLON.Matrix.Identity();
  90968. _this._worldToDevice = BABYLON.Matrix.Identity();
  90969. /**
  90970. * References to the webVR controllers for the vrDevice.
  90971. */
  90972. _this.controllers = [];
  90973. /**
  90974. * Emits an event when a controller is attached.
  90975. */
  90976. _this.onControllersAttachedObservable = new BABYLON.Observable();
  90977. /**
  90978. * Emits an event when a controller's mesh has been loaded;
  90979. */
  90980. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90981. /**
  90982. * If the rig cameras be used as parent instead of this camera.
  90983. */
  90984. _this.rigParenting = true;
  90985. _this._defaultHeight = undefined;
  90986. _this._workingVector = BABYLON.Vector3.Zero();
  90987. _this._oneVector = BABYLON.Vector3.One();
  90988. _this._workingMatrix = BABYLON.Matrix.Identity();
  90989. _this._cache.position = BABYLON.Vector3.Zero();
  90990. if (webVROptions.defaultHeight) {
  90991. _this._defaultHeight = webVROptions.defaultHeight;
  90992. _this.position.y = _this._defaultHeight;
  90993. }
  90994. _this.minZ = 0.1;
  90995. //legacy support - the compensation boolean was removed.
  90996. if (arguments.length === 5) {
  90997. _this.webVROptions = arguments[4];
  90998. }
  90999. // default webVR options
  91000. if (_this.webVROptions.trackPosition == undefined) {
  91001. _this.webVROptions.trackPosition = true;
  91002. }
  91003. if (_this.webVROptions.controllerMeshes == undefined) {
  91004. _this.webVROptions.controllerMeshes = true;
  91005. }
  91006. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  91007. _this.webVROptions.defaultLightingOnControllers = true;
  91008. }
  91009. _this.rotationQuaternion = new BABYLON.Quaternion();
  91010. if (_this.webVROptions && _this.webVROptions.positionScale) {
  91011. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  91012. }
  91013. //enable VR
  91014. var engine = _this.getEngine();
  91015. _this._onVREnabled = function (success) { if (success) {
  91016. _this.initControllers();
  91017. } };
  91018. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  91019. engine.initWebVR().add(function (event) {
  91020. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  91021. return;
  91022. }
  91023. _this._vrDevice = event.vrDisplay;
  91024. //reset the rig parameters.
  91025. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  91026. if (_this._attached) {
  91027. _this.getEngine().enableVR();
  91028. }
  91029. });
  91030. if (typeof (VRFrameData) !== "undefined")
  91031. _this._frameData = new VRFrameData();
  91032. /**
  91033. * The idea behind the following lines:
  91034. * objects that have the camera as parent should actually have the rig cameras as a parent.
  91035. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  91036. * the second will not show it correctly.
  91037. *
  91038. * To solve this - each object that has the camera as parent will be added to a protected array.
  91039. * When the rig camera renders, it will take this array and set all of those to be its children.
  91040. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  91041. * Amazing!
  91042. */
  91043. scene.onBeforeCameraRenderObservable.add(function (camera) {
  91044. if (camera.parent === _this && _this.rigParenting) {
  91045. _this._descendants = _this.getDescendants(true, function (n) {
  91046. // don't take the cameras or the controllers!
  91047. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  91048. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  91049. return !isController && !isRigCamera;
  91050. });
  91051. _this._descendants.forEach(function (node) {
  91052. node.parent = camera;
  91053. });
  91054. }
  91055. });
  91056. scene.onAfterCameraRenderObservable.add(function (camera) {
  91057. if (camera.parent === _this && _this.rigParenting) {
  91058. _this._descendants.forEach(function (node) {
  91059. node.parent = _this;
  91060. });
  91061. }
  91062. });
  91063. return _this;
  91064. }
  91065. /**
  91066. * Gets the device distance from the ground in meters.
  91067. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  91068. */
  91069. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  91070. if (this._standingMatrix) {
  91071. // Add standing matrix offset to get real offset from ground in room
  91072. this._standingMatrix.getTranslationToRef(this._workingVector);
  91073. return this._deviceRoomPosition.y + this._workingVector.y;
  91074. }
  91075. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  91076. return this._defaultHeight || 0;
  91077. };
  91078. /**
  91079. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91080. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  91081. */
  91082. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  91083. var _this = this;
  91084. if (callback === void 0) { callback = function (bool) { }; }
  91085. // Use standing matrix if available
  91086. this.getEngine().initWebVRAsync().then(function (result) {
  91087. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  91088. callback(false);
  91089. }
  91090. else {
  91091. _this._standingMatrix = new BABYLON.Matrix();
  91092. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  91093. if (!_this.getScene().useRightHandedSystem) {
  91094. [2, 6, 8, 9, 14].forEach(function (num) {
  91095. if (_this._standingMatrix) {
  91096. _this._standingMatrix.m[num] *= -1;
  91097. }
  91098. });
  91099. }
  91100. callback(true);
  91101. }
  91102. });
  91103. };
  91104. /**
  91105. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91106. * @returns A promise with a boolean set to if the standing matrix is supported.
  91107. */
  91108. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  91109. var _this = this;
  91110. return new Promise(function (res, rej) {
  91111. _this.useStandingMatrix(function (supported) {
  91112. res(supported);
  91113. });
  91114. });
  91115. };
  91116. /**
  91117. * Disposes the camera
  91118. */
  91119. WebVRFreeCamera.prototype.dispose = function () {
  91120. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  91121. _super.prototype.dispose.call(this);
  91122. };
  91123. /**
  91124. * Gets a vrController by name.
  91125. * @param name The name of the controller to retreive
  91126. * @returns the controller matching the name specified or null if not found
  91127. */
  91128. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  91129. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  91130. var gp = _a[_i];
  91131. if (gp.hand === name) {
  91132. return gp;
  91133. }
  91134. }
  91135. return null;
  91136. };
  91137. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  91138. /**
  91139. * The controller corrisponding to the users left hand.
  91140. */
  91141. get: function () {
  91142. if (!this._leftController) {
  91143. this._leftController = this.getControllerByName("left");
  91144. }
  91145. return this._leftController;
  91146. },
  91147. enumerable: true,
  91148. configurable: true
  91149. });
  91150. ;
  91151. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  91152. /**
  91153. * The controller corrisponding to the users right hand.
  91154. */
  91155. get: function () {
  91156. if (!this._rightController) {
  91157. this._rightController = this.getControllerByName("right");
  91158. }
  91159. return this._rightController;
  91160. },
  91161. enumerable: true,
  91162. configurable: true
  91163. });
  91164. ;
  91165. /**
  91166. * Casts a ray forward from the vrCamera's gaze.
  91167. * @param length Length of the ray (default: 100)
  91168. * @returns the ray corrisponding to the gaze
  91169. */
  91170. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  91171. if (length === void 0) { length = 100; }
  91172. if (this.leftCamera) {
  91173. // Use left eye to avoid computation to compute center on every call
  91174. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  91175. }
  91176. else {
  91177. return _super.prototype.getForwardRay.call(this, length);
  91178. }
  91179. };
  91180. /**
  91181. * Updates the camera based on device's frame data
  91182. */
  91183. WebVRFreeCamera.prototype._checkInputs = function () {
  91184. if (this._vrDevice && this._vrDevice.isPresenting) {
  91185. this._vrDevice.getFrameData(this._frameData);
  91186. this.updateFromDevice(this._frameData.pose);
  91187. }
  91188. _super.prototype._checkInputs.call(this);
  91189. };
  91190. /**
  91191. * Updates the poseControlled values based on the input device pose.
  91192. * @param poseData Pose coming from the device
  91193. */
  91194. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  91195. if (poseData && poseData.orientation) {
  91196. this.rawPose = poseData;
  91197. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  91198. if (this.getScene().useRightHandedSystem) {
  91199. this._deviceRoomRotationQuaternion.z *= -1;
  91200. this._deviceRoomRotationQuaternion.w *= -1;
  91201. }
  91202. if (this.webVROptions.trackPosition && this.rawPose.position) {
  91203. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  91204. if (this.getScene().useRightHandedSystem) {
  91205. this._deviceRoomPosition.z *= -1;
  91206. }
  91207. }
  91208. }
  91209. };
  91210. /**
  91211. * WebVR's attach control will start broadcasting frames to the device.
  91212. * Note that in certain browsers (chrome for example) this function must be called
  91213. * within a user-interaction callback. Example:
  91214. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  91215. *
  91216. * @param element html element to attach the vrDevice to
  91217. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  91218. */
  91219. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  91220. _super.prototype.attachControl.call(this, element, noPreventDefault);
  91221. this._attached = true;
  91222. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  91223. if (this._vrDevice) {
  91224. this.getEngine().enableVR();
  91225. }
  91226. };
  91227. /**
  91228. * Detaches the camera from the html element and disables VR
  91229. *
  91230. * @param element html element to detach from
  91231. */
  91232. WebVRFreeCamera.prototype.detachControl = function (element) {
  91233. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  91234. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  91235. _super.prototype.detachControl.call(this, element);
  91236. this._attached = false;
  91237. this.getEngine().disableVR();
  91238. };
  91239. /**
  91240. * @returns the name of this class
  91241. */
  91242. WebVRFreeCamera.prototype.getClassName = function () {
  91243. return "WebVRFreeCamera";
  91244. };
  91245. /**
  91246. * Calls resetPose on the vrDisplay
  91247. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  91248. */
  91249. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  91250. //uses the vrDisplay's "resetPose()".
  91251. //pitch and roll won't be affected.
  91252. this._vrDevice.resetPose();
  91253. };
  91254. /**
  91255. * Updates the rig cameras (left and right eye)
  91256. */
  91257. WebVRFreeCamera.prototype._updateRigCameras = function () {
  91258. var camLeft = this._rigCameras[0];
  91259. var camRight = this._rigCameras[1];
  91260. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91261. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91262. camLeft.position.copyFrom(this._deviceRoomPosition);
  91263. camRight.position.copyFrom(this._deviceRoomPosition);
  91264. };
  91265. /**
  91266. * Updates the cached values of the camera
  91267. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  91268. */
  91269. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  91270. var _this = this;
  91271. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  91272. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  91273. if (!this.updateCacheCalled) {
  91274. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  91275. this.updateCacheCalled = true;
  91276. this.update();
  91277. }
  91278. // Set working vector to the device position in room space rotated by the new rotation
  91279. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  91280. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  91281. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  91282. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  91283. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  91284. // Add translation from anchor position
  91285. this._deviceToWorld.getTranslationToRef(this._workingVector);
  91286. this._workingVector.addInPlace(this.position);
  91287. this._workingVector.subtractInPlace(this._cache.position);
  91288. this._deviceToWorld.setTranslation(this._workingVector);
  91289. // Set an inverted matrix to be used when updating the camera
  91290. this._deviceToWorld.invertToRef(this._worldToDevice);
  91291. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  91292. this.controllers.forEach(function (controller) {
  91293. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  91294. controller.update();
  91295. });
  91296. }
  91297. if (!ignoreParentClass) {
  91298. _super.prototype._updateCache.call(this);
  91299. }
  91300. this.updateCacheCalled = false;
  91301. };
  91302. /**
  91303. * Updates the current device position and rotation in the babylon world
  91304. */
  91305. WebVRFreeCamera.prototype.update = function () {
  91306. // Get current device position in babylon world
  91307. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  91308. // Get current device rotation in babylon world
  91309. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  91310. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  91311. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  91312. _super.prototype.update.call(this);
  91313. };
  91314. /**
  91315. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  91316. * @returns an identity matrix
  91317. */
  91318. WebVRFreeCamera.prototype._getViewMatrix = function () {
  91319. return BABYLON.Matrix.Identity();
  91320. };
  91321. /**
  91322. * This function is called by the two RIG cameras.
  91323. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  91324. */
  91325. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  91326. var _this = this;
  91327. // Update the parent camera prior to using a child camera to avoid desynchronization
  91328. var parentCamera = this._cameraRigParams["parentCamera"];
  91329. parentCamera._updateCache();
  91330. //WebVR 1.1
  91331. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  91332. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  91333. if (!this.getScene().useRightHandedSystem) {
  91334. [2, 6, 8, 9, 14].forEach(function (num) {
  91335. _this._webvrViewMatrix.m[num] *= -1;
  91336. });
  91337. }
  91338. // update the camera rotation matrix
  91339. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  91340. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  91341. // Computing target and final matrix
  91342. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  91343. // should the view matrix be updated with scale and position offset?
  91344. if (parentCamera.deviceScaleFactor !== 1) {
  91345. this._webvrViewMatrix.invert();
  91346. // scale the position, if set
  91347. if (parentCamera.deviceScaleFactor) {
  91348. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  91349. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  91350. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  91351. }
  91352. this._webvrViewMatrix.invert();
  91353. }
  91354. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  91355. // Compute global position
  91356. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  91357. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  91358. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  91359. this._workingMatrix.getTranslationToRef(this._globalPosition);
  91360. this._markSyncedWithParent();
  91361. return this._webvrViewMatrix;
  91362. };
  91363. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  91364. var _this = this;
  91365. var parentCamera = this.parent;
  91366. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  91367. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  91368. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  91369. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  91370. //babylon compatible matrix
  91371. if (!this.getScene().useRightHandedSystem) {
  91372. [8, 9, 10, 11].forEach(function (num) {
  91373. _this._projectionMatrix.m[num] *= -1;
  91374. });
  91375. }
  91376. return this._projectionMatrix;
  91377. };
  91378. /**
  91379. * Initializes the controllers and their meshes
  91380. */
  91381. WebVRFreeCamera.prototype.initControllers = function () {
  91382. var _this = this;
  91383. this.controllers = [];
  91384. var manager = this.getScene().gamepadManager;
  91385. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  91386. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91387. var webVrController = gamepad;
  91388. if (webVrController.defaultModel) {
  91389. webVrController.defaultModel.setEnabled(false);
  91390. }
  91391. if (webVrController.hand === "right") {
  91392. _this._rightController = null;
  91393. }
  91394. if (webVrController.hand === "left") {
  91395. _this._leftController = null;
  91396. }
  91397. var controllerIndex = _this.controllers.indexOf(webVrController);
  91398. if (controllerIndex !== -1) {
  91399. _this.controllers.splice(controllerIndex, 1);
  91400. }
  91401. }
  91402. });
  91403. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  91404. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91405. var webVrController_1 = gamepad;
  91406. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  91407. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  91408. if (_this.webVROptions.controllerMeshes) {
  91409. if (webVrController_1.defaultModel) {
  91410. webVrController_1.defaultModel.setEnabled(true);
  91411. }
  91412. else {
  91413. // Load the meshes
  91414. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  91415. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  91416. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  91417. if (_this.webVROptions.defaultLightingOnControllers) {
  91418. if (!_this._lightOnControllers) {
  91419. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  91420. }
  91421. var activateLightOnSubMeshes_1 = function (mesh, light) {
  91422. var children = mesh.getChildren();
  91423. if (children.length !== 0) {
  91424. children.forEach(function (mesh) {
  91425. light.includedOnlyMeshes.push(mesh);
  91426. activateLightOnSubMeshes_1(mesh, light);
  91427. });
  91428. }
  91429. };
  91430. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  91431. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  91432. }
  91433. });
  91434. }
  91435. }
  91436. webVrController_1.attachToPoseControlledCamera(_this);
  91437. // since this is async - sanity check. Is the controller already stored?
  91438. if (_this.controllers.indexOf(webVrController_1) === -1) {
  91439. //add to the controllers array
  91440. _this.controllers.push(webVrController_1);
  91441. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  91442. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  91443. // So we're overriding setting left & right manually to be sure
  91444. var firstViveWandDetected = false;
  91445. for (var i = 0; i < _this.controllers.length; i++) {
  91446. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91447. if (!firstViveWandDetected) {
  91448. firstViveWandDetected = true;
  91449. _this.controllers[i].hand = "left";
  91450. }
  91451. else {
  91452. _this.controllers[i].hand = "right";
  91453. }
  91454. }
  91455. }
  91456. //did we find enough controllers? Great! let the developer know.
  91457. if (_this.controllers.length >= 2) {
  91458. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  91459. }
  91460. }
  91461. }
  91462. });
  91463. };
  91464. return WebVRFreeCamera;
  91465. }(BABYLON.FreeCamera));
  91466. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  91467. })(BABYLON || (BABYLON = {}));
  91468. //# sourceMappingURL=babylon.webVRCamera.js.map
  91469. var BABYLON;
  91470. (function (BABYLON) {
  91471. // We're mainly based on the logic defined into the FreeCamera code
  91472. /**
  91473. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  91474. * being tilted forward or back and left or right.
  91475. */
  91476. var DeviceOrientationCamera = /** @class */ (function (_super) {
  91477. __extends(DeviceOrientationCamera, _super);
  91478. /**
  91479. * Creates a new device orientation camera
  91480. * @param name The name of the camera
  91481. * @param position The start position camera
  91482. * @param scene The scene the camera belongs to
  91483. */
  91484. function DeviceOrientationCamera(name, position, scene) {
  91485. var _this = _super.call(this, name, position, scene) || this;
  91486. _this._quaternionCache = new BABYLON.Quaternion();
  91487. _this.inputs.addDeviceOrientation();
  91488. return _this;
  91489. }
  91490. /**
  91491. * Gets the current instance class name ("DeviceOrientationCamera").
  91492. * This helps avoiding instanceof at run time.
  91493. * @returns the class name
  91494. */
  91495. DeviceOrientationCamera.prototype.getClassName = function () {
  91496. return "DeviceOrientationCamera";
  91497. };
  91498. /**
  91499. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  91500. */
  91501. DeviceOrientationCamera.prototype._checkInputs = function () {
  91502. _super.prototype._checkInputs.call(this);
  91503. this._quaternionCache.copyFrom(this.rotationQuaternion);
  91504. if (this._initialQuaternion) {
  91505. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91506. }
  91507. };
  91508. /**
  91509. * Reset the camera to its default orientation on the specified axis only.
  91510. * @param axis The axis to reset
  91511. */
  91512. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  91513. var _this = this;
  91514. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  91515. //can only work if this camera has a rotation quaternion already.
  91516. if (!this.rotationQuaternion)
  91517. return;
  91518. if (!this._initialQuaternion) {
  91519. this._initialQuaternion = new BABYLON.Quaternion();
  91520. }
  91521. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  91522. ['x', 'y', 'z'].forEach(function (axisName) {
  91523. if (!axis[axisName]) {
  91524. _this._initialQuaternion[axisName] = 0;
  91525. }
  91526. else {
  91527. _this._initialQuaternion[axisName] *= -1;
  91528. }
  91529. });
  91530. this._initialQuaternion.normalize();
  91531. //force rotation update
  91532. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91533. };
  91534. return DeviceOrientationCamera;
  91535. }(BABYLON.FreeCamera));
  91536. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  91537. })(BABYLON || (BABYLON = {}));
  91538. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  91539. var BABYLON;
  91540. (function (BABYLON) {
  91541. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  91542. __extends(VRDeviceOrientationFreeCamera, _super);
  91543. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91544. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91545. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91546. var _this = _super.call(this, name, position, scene) || this;
  91547. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91548. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91549. return _this;
  91550. }
  91551. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  91552. return "VRDeviceOrientationFreeCamera";
  91553. };
  91554. return VRDeviceOrientationFreeCamera;
  91555. }(BABYLON.DeviceOrientationCamera));
  91556. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  91557. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  91558. __extends(VRDeviceOrientationGamepadCamera, _super);
  91559. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91560. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91561. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91562. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  91563. _this.inputs.addGamepad();
  91564. return _this;
  91565. }
  91566. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  91567. return "VRDeviceOrientationGamepadCamera";
  91568. };
  91569. return VRDeviceOrientationGamepadCamera;
  91570. }(VRDeviceOrientationFreeCamera));
  91571. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  91572. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  91573. __extends(VRDeviceOrientationArcRotateCamera, _super);
  91574. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  91575. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91576. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91577. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91578. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91579. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91580. _this.inputs.addVRDeviceOrientation();
  91581. return _this;
  91582. }
  91583. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  91584. return "VRDeviceOrientationArcRotateCamera";
  91585. };
  91586. return VRDeviceOrientationArcRotateCamera;
  91587. }(BABYLON.ArcRotateCamera));
  91588. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  91589. })(BABYLON || (BABYLON = {}));
  91590. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  91591. var BABYLON;
  91592. (function (BABYLON) {
  91593. /**
  91594. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91595. */
  91596. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91597. __extends(AnaglyphFreeCamera, _super);
  91598. /**
  91599. * Creates a new AnaglyphFreeCamera
  91600. * @param name defines camera name
  91601. * @param position defines initial position
  91602. * @param interaxialDistance defines distance between each color axis
  91603. * @param scene defines the hosting scene
  91604. */
  91605. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91606. var _this = _super.call(this, name, position, scene) || this;
  91607. _this.interaxialDistance = interaxialDistance;
  91608. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91609. return _this;
  91610. }
  91611. /**
  91612. * Gets camera class name
  91613. * @returns AnaglyphFreeCamera
  91614. */
  91615. AnaglyphFreeCamera.prototype.getClassName = function () {
  91616. return "AnaglyphFreeCamera";
  91617. };
  91618. return AnaglyphFreeCamera;
  91619. }(BABYLON.FreeCamera));
  91620. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91621. /**
  91622. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91623. */
  91624. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91625. __extends(AnaglyphArcRotateCamera, _super);
  91626. /**
  91627. * Creates a new AnaglyphArcRotateCamera
  91628. * @param name defines camera name
  91629. * @param alpha defines alpha angle (in radians)
  91630. * @param beta defines beta angle (in radians)
  91631. * @param radius defines radius
  91632. * @param target defines camera target
  91633. * @param interaxialDistance defines distance between each color axis
  91634. * @param scene defines the hosting scene
  91635. */
  91636. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91637. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91638. _this.interaxialDistance = interaxialDistance;
  91639. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91640. return _this;
  91641. }
  91642. /**
  91643. * Gets camera class name
  91644. * @returns AnaglyphArcRotateCamera
  91645. */
  91646. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91647. return "AnaglyphArcRotateCamera";
  91648. };
  91649. return AnaglyphArcRotateCamera;
  91650. }(BABYLON.ArcRotateCamera));
  91651. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91652. /**
  91653. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91654. */
  91655. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91656. __extends(AnaglyphGamepadCamera, _super);
  91657. /**
  91658. * Creates a new AnaglyphGamepadCamera
  91659. * @param name defines camera name
  91660. * @param position defines initial position
  91661. * @param interaxialDistance defines distance between each color axis
  91662. * @param scene defines the hosting scene
  91663. */
  91664. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91665. var _this = _super.call(this, name, position, scene) || this;
  91666. _this.interaxialDistance = interaxialDistance;
  91667. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91668. return _this;
  91669. }
  91670. /**
  91671. * Gets camera class name
  91672. * @returns AnaglyphGamepadCamera
  91673. */
  91674. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91675. return "AnaglyphGamepadCamera";
  91676. };
  91677. return AnaglyphGamepadCamera;
  91678. }(BABYLON.GamepadCamera));
  91679. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91680. /**
  91681. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91682. */
  91683. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91684. __extends(AnaglyphUniversalCamera, _super);
  91685. /**
  91686. * Creates a new AnaglyphUniversalCamera
  91687. * @param name defines camera name
  91688. * @param position defines initial position
  91689. * @param interaxialDistance defines distance between each color axis
  91690. * @param scene defines the hosting scene
  91691. */
  91692. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91693. var _this = _super.call(this, name, position, scene) || this;
  91694. _this.interaxialDistance = interaxialDistance;
  91695. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91696. return _this;
  91697. }
  91698. /**
  91699. * Gets camera class name
  91700. * @returns AnaglyphUniversalCamera
  91701. */
  91702. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91703. return "AnaglyphUniversalCamera";
  91704. };
  91705. return AnaglyphUniversalCamera;
  91706. }(BABYLON.UniversalCamera));
  91707. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91708. /**
  91709. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91710. */
  91711. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91712. __extends(StereoscopicFreeCamera, _super);
  91713. /**
  91714. * Creates a new StereoscopicFreeCamera
  91715. * @param name defines camera name
  91716. * @param position defines initial position
  91717. * @param interaxialDistance defines distance between each color axis
  91718. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91719. * @param scene defines the hosting scene
  91720. */
  91721. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91722. var _this = _super.call(this, name, position, scene) || this;
  91723. _this.interaxialDistance = interaxialDistance;
  91724. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91725. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91726. return _this;
  91727. }
  91728. /**
  91729. * Gets camera class name
  91730. * @returns StereoscopicFreeCamera
  91731. */
  91732. StereoscopicFreeCamera.prototype.getClassName = function () {
  91733. return "StereoscopicFreeCamera";
  91734. };
  91735. return StereoscopicFreeCamera;
  91736. }(BABYLON.FreeCamera));
  91737. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91738. /**
  91739. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91740. */
  91741. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91742. __extends(StereoscopicArcRotateCamera, _super);
  91743. /**
  91744. * Creates a new StereoscopicArcRotateCamera
  91745. * @param name defines camera name
  91746. * @param alpha defines alpha angle (in radians)
  91747. * @param beta defines beta angle (in radians)
  91748. * @param radius defines radius
  91749. * @param target defines camera target
  91750. * @param interaxialDistance defines distance between each color axis
  91751. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91752. * @param scene defines the hosting scene
  91753. */
  91754. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91755. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91756. _this.interaxialDistance = interaxialDistance;
  91757. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91758. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91759. return _this;
  91760. }
  91761. /**
  91762. * Gets camera class name
  91763. * @returns StereoscopicArcRotateCamera
  91764. */
  91765. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91766. return "StereoscopicArcRotateCamera";
  91767. };
  91768. return StereoscopicArcRotateCamera;
  91769. }(BABYLON.ArcRotateCamera));
  91770. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91771. /**
  91772. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91773. */
  91774. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91775. __extends(StereoscopicGamepadCamera, _super);
  91776. /**
  91777. * Creates a new StereoscopicGamepadCamera
  91778. * @param name defines camera name
  91779. * @param position defines initial position
  91780. * @param interaxialDistance defines distance between each color axis
  91781. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91782. * @param scene defines the hosting scene
  91783. */
  91784. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91785. var _this = _super.call(this, name, position, scene) || this;
  91786. _this.interaxialDistance = interaxialDistance;
  91787. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91788. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91789. return _this;
  91790. }
  91791. /**
  91792. * Gets camera class name
  91793. * @returns StereoscopicGamepadCamera
  91794. */
  91795. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91796. return "StereoscopicGamepadCamera";
  91797. };
  91798. return StereoscopicGamepadCamera;
  91799. }(BABYLON.GamepadCamera));
  91800. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91801. /**
  91802. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91803. */
  91804. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91805. __extends(StereoscopicUniversalCamera, _super);
  91806. /**
  91807. * Creates a new StereoscopicUniversalCamera
  91808. * @param name defines camera name
  91809. * @param position defines initial position
  91810. * @param interaxialDistance defines distance between each color axis
  91811. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91812. * @param scene defines the hosting scene
  91813. */
  91814. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91815. var _this = _super.call(this, name, position, scene) || this;
  91816. _this.interaxialDistance = interaxialDistance;
  91817. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91818. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91819. return _this;
  91820. }
  91821. /**
  91822. * Gets camera class name
  91823. * @returns StereoscopicUniversalCamera
  91824. */
  91825. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91826. return "StereoscopicUniversalCamera";
  91827. };
  91828. return StereoscopicUniversalCamera;
  91829. }(BABYLON.UniversalCamera));
  91830. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91831. })(BABYLON || (BABYLON = {}));
  91832. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  91833. var BABYLON;
  91834. (function (BABYLON) {
  91835. var VRExperienceHelperGazer = /** @class */ (function () {
  91836. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  91837. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  91838. this.scene = scene;
  91839. this._pointerDownOnMeshAsked = false;
  91840. this._isActionableMesh = false;
  91841. this._teleportationRequestInitiated = false;
  91842. this._teleportationBackRequestInitiated = false;
  91843. this._rotationRightAsked = false;
  91844. this._rotationLeftAsked = false;
  91845. this._dpadPressed = true;
  91846. this._activePointer = false;
  91847. this._id = VRExperienceHelperGazer._idCounter++;
  91848. // Gaze tracker
  91849. if (!gazeTrackerToClone) {
  91850. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  91851. this._gazeTracker.bakeCurrentTransformIntoVertices();
  91852. this._gazeTracker.isPickable = false;
  91853. this._gazeTracker.isVisible = false;
  91854. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  91855. targetMat.specularColor = BABYLON.Color3.Black();
  91856. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91857. targetMat.backFaceCulling = false;
  91858. this._gazeTracker.material = targetMat;
  91859. }
  91860. else {
  91861. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  91862. }
  91863. }
  91864. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  91865. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  91866. };
  91867. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  91868. this._pointerDownOnMeshAsked = true;
  91869. if (this._currentHit) {
  91870. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  91871. }
  91872. };
  91873. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  91874. if (this._currentHit) {
  91875. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  91876. }
  91877. this._pointerDownOnMeshAsked = false;
  91878. };
  91879. VRExperienceHelperGazer.prototype._activatePointer = function () {
  91880. this._activePointer = true;
  91881. };
  91882. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  91883. this._activePointer = false;
  91884. };
  91885. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  91886. if (distance === void 0) { distance = 100; }
  91887. };
  91888. VRExperienceHelperGazer.prototype.dispose = function () {
  91889. this._interactionsEnabled = false;
  91890. this._teleportationEnabled = false;
  91891. if (this._gazeTracker) {
  91892. this._gazeTracker.dispose();
  91893. }
  91894. };
  91895. VRExperienceHelperGazer._idCounter = 0;
  91896. return VRExperienceHelperGazer;
  91897. }());
  91898. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  91899. __extends(VRExperienceHelperControllerGazer, _super);
  91900. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  91901. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  91902. _this.webVRController = webVRController;
  91903. // Laser pointer
  91904. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  91905. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  91906. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91907. laserPointerMaterial.alpha = 0.6;
  91908. _this._laserPointer.material = laserPointerMaterial;
  91909. _this._laserPointer.rotation.x = Math.PI / 2;
  91910. _this._laserPointer.position.z = -0.5;
  91911. _this._laserPointer.isVisible = false;
  91912. _this._laserPointer.isPickable = false;
  91913. if (!webVRController.mesh) {
  91914. // Create an empty mesh that is used prior to loading the high quality model
  91915. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  91916. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  91917. preloadPointerPose.rotation.x = -0.7;
  91918. preloadMesh.addChild(preloadPointerPose);
  91919. webVRController.attachToMesh(preloadMesh);
  91920. }
  91921. _this._setLaserPointerParent(webVRController.mesh);
  91922. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  91923. _this._setLaserPointerParent(mesh);
  91924. });
  91925. return _this;
  91926. }
  91927. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  91928. return this.webVRController.getForwardRay(length);
  91929. };
  91930. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  91931. _super.prototype._activatePointer.call(this);
  91932. this._laserPointer.isVisible = true;
  91933. };
  91934. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  91935. _super.prototype._deactivatePointer.call(this);
  91936. this._laserPointer.isVisible = false;
  91937. };
  91938. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  91939. this._laserPointer.material.emissiveColor = color;
  91940. };
  91941. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  91942. var makeNotPick = function (root) {
  91943. root.name += " laserPointer";
  91944. root.isPickable = false;
  91945. root.getChildMeshes().forEach(function (c) {
  91946. makeNotPick(c);
  91947. });
  91948. };
  91949. makeNotPick(mesh);
  91950. var childMeshes = mesh.getChildMeshes();
  91951. this.webVRController._pointingPoseNode = null;
  91952. for (var i = 0; i < childMeshes.length; i++) {
  91953. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  91954. mesh = childMeshes[i];
  91955. this.webVRController._pointingPoseNode = mesh;
  91956. break;
  91957. }
  91958. }
  91959. this._laserPointer.parent = mesh;
  91960. };
  91961. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  91962. if (distance === void 0) { distance = 100; }
  91963. this._laserPointer.scaling.y = distance;
  91964. this._laserPointer.position.z = -distance / 2;
  91965. };
  91966. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  91967. _super.prototype.dispose.call(this);
  91968. this._laserPointer.dispose();
  91969. if (this._meshAttachedObserver) {
  91970. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  91971. }
  91972. };
  91973. return VRExperienceHelperControllerGazer;
  91974. }(VRExperienceHelperGazer));
  91975. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  91976. __extends(VRExperienceHelperCameraGazer, _super);
  91977. function VRExperienceHelperCameraGazer(getCamera, scene) {
  91978. var _this = _super.call(this, scene) || this;
  91979. _this.getCamera = getCamera;
  91980. return _this;
  91981. }
  91982. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  91983. var camera = this.getCamera();
  91984. if (camera) {
  91985. return camera.getForwardRay(length);
  91986. }
  91987. else {
  91988. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  91989. }
  91990. };
  91991. return VRExperienceHelperCameraGazer;
  91992. }(VRExperienceHelperGazer));
  91993. /**
  91994. * Helps to quickly add VR support to an existing scene.
  91995. * See http://doc.babylonjs.com/how_to/webvr_helper
  91996. */
  91997. var VRExperienceHelper = /** @class */ (function () {
  91998. /**
  91999. * Instantiates a VRExperienceHelper.
  92000. * Helps to quickly add VR support to an existing scene.
  92001. * @param scene The scene the VRExperienceHelper belongs to.
  92002. * @param webVROptions Options to modify the vr experience helper's behavior.
  92003. */
  92004. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92005. if (webVROptions === void 0) { webVROptions = {}; }
  92006. var _this = this;
  92007. this.webVROptions = webVROptions;
  92008. // Can the system support WebVR, even if a headset isn't plugged in?
  92009. this._webVRsupported = false;
  92010. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92011. this._webVRready = false;
  92012. // Are we waiting for the requestPresent callback to complete?
  92013. this._webVRrequesting = false;
  92014. // Are we presenting to the headset right now?
  92015. this._webVRpresenting = false;
  92016. // Are we presenting in the fullscreen fallback?
  92017. this._fullscreenVRpresenting = false;
  92018. /**
  92019. * Observable raised when entering VR.
  92020. */
  92021. this.onEnteringVRObservable = new BABYLON.Observable();
  92022. /**
  92023. * Observable raised when exiting VR.
  92024. */
  92025. this.onExitingVRObservable = new BABYLON.Observable();
  92026. /**
  92027. * Observable raised when controller mesh is loaded.
  92028. */
  92029. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92030. this._useCustomVRButton = false;
  92031. this._teleportationRequested = false;
  92032. this._teleportActive = false;
  92033. this._floorMeshesCollection = [];
  92034. this._rotationAllowed = true;
  92035. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92036. this._isDefaultTeleportationTarget = true;
  92037. this._teleportationFillColor = "#444444";
  92038. this._teleportationBorderColor = "#FFFFFF";
  92039. this._rotationAngle = 0;
  92040. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92041. this._padSensibilityUp = 0.65;
  92042. this._padSensibilityDown = 0.35;
  92043. this.leftController = null;
  92044. this.rightController = null;
  92045. /**
  92046. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92047. */
  92048. this.onNewMeshSelected = new BABYLON.Observable();
  92049. /**
  92050. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92051. */
  92052. this.onNewMeshPicked = new BABYLON.Observable();
  92053. /**
  92054. * Observable raised before camera teleportation
  92055. */
  92056. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92057. /**
  92058. * Observable raised after camera teleportation
  92059. */
  92060. this.onAfterCameraTeleport = new BABYLON.Observable();
  92061. /**
  92062. * Observable raised when current selected mesh gets unselected
  92063. */
  92064. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92065. /**
  92066. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92067. */
  92068. this.teleportationEnabled = true;
  92069. this._teleportationInitialized = false;
  92070. this._interactionsEnabled = false;
  92071. this._interactionsRequested = false;
  92072. this._displayGaze = true;
  92073. this._displayLaserPointer = true;
  92074. this._onResize = function () {
  92075. _this.moveButtonToBottomRight();
  92076. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92077. _this.exitVR();
  92078. }
  92079. };
  92080. this._onFullscreenChange = function () {
  92081. if (document.fullscreen !== undefined) {
  92082. _this._fullscreenVRpresenting = document.fullscreen;
  92083. }
  92084. else if (document.mozFullScreen !== undefined) {
  92085. _this._fullscreenVRpresenting = document.mozFullScreen;
  92086. }
  92087. else if (document.webkitIsFullScreen !== undefined) {
  92088. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92089. }
  92090. else if (document.msIsFullScreen !== undefined) {
  92091. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92092. }
  92093. else if (document.msFullscreenElement !== undefined) {
  92094. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92095. }
  92096. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92097. _this.exitVR();
  92098. if (!_this._useCustomVRButton) {
  92099. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92100. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92101. }
  92102. }
  92103. };
  92104. this.beforeRender = function () {
  92105. if (_this.leftController && _this.leftController._activePointer) {
  92106. _this._castRayAndSelectObject(_this.leftController);
  92107. }
  92108. if (_this.rightController && _this.rightController._activePointer) {
  92109. _this._castRayAndSelectObject(_this.rightController);
  92110. }
  92111. if (_this._noControllerIsActive) {
  92112. _this._castRayAndSelectObject(_this._cameraGazer);
  92113. }
  92114. else {
  92115. _this._cameraGazer._gazeTracker.isVisible = false;
  92116. }
  92117. };
  92118. this._onNewGamepadConnected = function (gamepad) {
  92119. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92120. if (gamepad.leftStick) {
  92121. gamepad.onleftstickchanged(function (stickValues) {
  92122. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92123. // Listening to classic/xbox gamepad only if no VR controller is active
  92124. if ((!_this.leftController && !_this.rightController) ||
  92125. ((_this.leftController && !_this.leftController._activePointer) &&
  92126. (_this.rightController && !_this.rightController._activePointer))) {
  92127. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92128. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92129. }
  92130. }
  92131. });
  92132. }
  92133. if (gamepad.rightStick) {
  92134. gamepad.onrightstickchanged(function (stickValues) {
  92135. if (_this._teleportationInitialized) {
  92136. _this._checkRotate(stickValues, _this._cameraGazer);
  92137. }
  92138. });
  92139. }
  92140. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92141. gamepad.onbuttondown(function (buttonPressed) {
  92142. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92143. _this._cameraGazer._selectionPointerDown();
  92144. }
  92145. });
  92146. gamepad.onbuttonup(function (buttonPressed) {
  92147. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92148. _this._cameraGazer._selectionPointerUp();
  92149. }
  92150. });
  92151. }
  92152. }
  92153. else {
  92154. var webVRController = gamepad;
  92155. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92156. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92157. _this.rightController = controller;
  92158. }
  92159. else {
  92160. _this.leftController = controller;
  92161. }
  92162. _this._tryEnableInteractionOnController(controller);
  92163. }
  92164. };
  92165. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  92166. this._tryEnableInteractionOnController = function (controller) {
  92167. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92168. _this._enableInteractionOnController(controller);
  92169. }
  92170. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92171. _this._enableTeleportationOnController(controller);
  92172. }
  92173. };
  92174. this._onNewGamepadDisconnected = function (gamepad) {
  92175. if (gamepad instanceof BABYLON.WebVRController) {
  92176. if (gamepad.hand === "left" && _this.leftController != null) {
  92177. _this.leftController.dispose();
  92178. _this.leftController = null;
  92179. }
  92180. if (gamepad.hand === "right" && _this.rightController != null) {
  92181. _this.rightController.dispose();
  92182. _this.rightController = null;
  92183. }
  92184. }
  92185. };
  92186. this._workingVector = BABYLON.Vector3.Zero();
  92187. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92188. this._workingMatrix = BABYLON.Matrix.Identity();
  92189. this._scene = scene;
  92190. this._canvas = scene.getEngine().getRenderingCanvas();
  92191. // Parse options
  92192. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92193. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92194. }
  92195. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92196. webVROptions.createDeviceOrientationCamera = true;
  92197. }
  92198. if (webVROptions.laserToggle === undefined) {
  92199. webVROptions.laserToggle = true;
  92200. }
  92201. if (webVROptions.defaultHeight === undefined) {
  92202. webVROptions.defaultHeight = 1.7;
  92203. }
  92204. if (webVROptions.useCustomVRButton) {
  92205. this._useCustomVRButton = true;
  92206. if (webVROptions.customVRButton) {
  92207. this._btnVR = webVROptions.customVRButton;
  92208. }
  92209. }
  92210. if (webVROptions.rayLength) {
  92211. this._rayLength = webVROptions.rayLength;
  92212. }
  92213. this._defaultHeight = webVROptions.defaultHeight;
  92214. if (webVROptions.positionScale) {
  92215. this._rayLength *= webVROptions.positionScale;
  92216. this._defaultHeight *= webVROptions.positionScale;
  92217. }
  92218. // Set position
  92219. if (this._scene.activeCamera) {
  92220. this._position = this._scene.activeCamera.position.clone();
  92221. }
  92222. else {
  92223. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92224. }
  92225. // Set non-vr camera
  92226. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92227. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92228. // Copy data from existing camera
  92229. if (this._scene.activeCamera) {
  92230. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92231. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92232. // Set rotation from previous camera
  92233. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92234. var targetCamera = this._scene.activeCamera;
  92235. if (targetCamera.rotationQuaternion) {
  92236. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92237. }
  92238. else {
  92239. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92240. }
  92241. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92242. }
  92243. }
  92244. this._scene.activeCamera = this._deviceOrientationCamera;
  92245. if (this._canvas) {
  92246. this._scene.activeCamera.attachControl(this._canvas);
  92247. }
  92248. }
  92249. else {
  92250. this._existingCamera = this._scene.activeCamera;
  92251. }
  92252. // Create VR cameras
  92253. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92254. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92255. }
  92256. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92257. this._webVRCamera.useStandingMatrix();
  92258. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92259. // Create default button
  92260. if (!this._useCustomVRButton) {
  92261. this._btnVR = document.createElement("BUTTON");
  92262. this._btnVR.className = "babylonVRicon";
  92263. this._btnVR.id = "babylonVRiconbtn";
  92264. this._btnVR.title = "Click to switch to VR";
  92265. 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) }";
  92266. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92267. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92268. // css += ".babylonVRicon.vrdisplaysupported { }";
  92269. // css += ".babylonVRicon.vrdisplayready { }";
  92270. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92271. var style = document.createElement('style');
  92272. style.appendChild(document.createTextNode(css));
  92273. document.getElementsByTagName('head')[0].appendChild(style);
  92274. this.moveButtonToBottomRight();
  92275. }
  92276. // VR button click event
  92277. if (this._btnVR) {
  92278. this._btnVR.addEventListener("click", function () {
  92279. if (!_this.isInVRMode) {
  92280. _this.enterVR();
  92281. }
  92282. else {
  92283. _this.exitVR();
  92284. }
  92285. });
  92286. }
  92287. // Window events
  92288. window.addEventListener("resize", this._onResize);
  92289. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92290. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92291. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92292. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92293. document.onmsfullscreenchange = this._onFullscreenChange;
  92294. // Display vr button when headset is connected
  92295. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92296. this.displayVRButton();
  92297. }
  92298. else {
  92299. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92300. if (e.vrDisplay) {
  92301. _this.displayVRButton();
  92302. }
  92303. });
  92304. }
  92305. // Exiting VR mode using 'ESC' key on desktop
  92306. this._onKeyDown = function (event) {
  92307. if (event.keyCode === 27 && _this.isInVRMode) {
  92308. _this.exitVR();
  92309. }
  92310. };
  92311. document.addEventListener("keydown", this._onKeyDown);
  92312. // Exiting VR mode double tapping the touch screen
  92313. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92314. if (_this.isInVRMode) {
  92315. _this.exitVR();
  92316. if (_this._fullscreenVRpresenting) {
  92317. _this._scene.getEngine().switchFullscreen(true);
  92318. }
  92319. }
  92320. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92321. // Listen for WebVR display changes
  92322. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92323. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92324. this._onVRRequestPresentStart = function () {
  92325. _this._webVRrequesting = true;
  92326. _this.updateButtonVisibility();
  92327. };
  92328. this._onVRRequestPresentComplete = function (success) {
  92329. _this._webVRrequesting = false;
  92330. _this.updateButtonVisibility();
  92331. };
  92332. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92333. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92334. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92335. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92336. scene.onDisposeObservable.add(function () {
  92337. _this.dispose();
  92338. });
  92339. // Gamepad connection events
  92340. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92341. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92342. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92343. this.updateButtonVisibility();
  92344. //create easing functions
  92345. this._circleEase = new BABYLON.CircleEase();
  92346. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92347. if (this.webVROptions.floorMeshes) {
  92348. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92349. }
  92350. }
  92351. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92352. /** Return this.onEnteringVRObservable
  92353. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92354. */
  92355. get: function () {
  92356. return this.onEnteringVRObservable;
  92357. },
  92358. enumerable: true,
  92359. configurable: true
  92360. });
  92361. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92362. /** Return this.onExitingVRObservable
  92363. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92364. */
  92365. get: function () {
  92366. return this.onExitingVRObservable;
  92367. },
  92368. enumerable: true,
  92369. configurable: true
  92370. });
  92371. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92372. /** Return this.onControllerMeshLoadedObservable
  92373. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92374. */
  92375. get: function () {
  92376. return this.onControllerMeshLoadedObservable;
  92377. },
  92378. enumerable: true,
  92379. configurable: true
  92380. });
  92381. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92382. /**
  92383. * The mesh used to display where the user is going to teleport.
  92384. */
  92385. get: function () {
  92386. return this._teleportationTarget;
  92387. },
  92388. /**
  92389. * Sets the mesh to be used to display where the user is going to teleport.
  92390. */
  92391. set: function (value) {
  92392. if (value) {
  92393. value.name = "teleportationTarget";
  92394. this._isDefaultTeleportationTarget = false;
  92395. this._teleportationTarget = value;
  92396. }
  92397. },
  92398. enumerable: true,
  92399. configurable: true
  92400. });
  92401. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92402. /**
  92403. * The mesh used to display where the user is selecting,
  92404. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92405. * See http://doc.babylonjs.com/resources/baking_transformations
  92406. */
  92407. get: function () {
  92408. return this._cameraGazer._gazeTracker;
  92409. },
  92410. set: function (value) {
  92411. if (value) {
  92412. this._cameraGazer._gazeTracker = value;
  92413. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92414. this._cameraGazer._gazeTracker.isPickable = false;
  92415. this._cameraGazer._gazeTracker.isVisible = false;
  92416. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92417. if (this.leftController) {
  92418. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92419. }
  92420. if (this.rightController) {
  92421. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92422. }
  92423. }
  92424. },
  92425. enumerable: true,
  92426. configurable: true
  92427. });
  92428. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92429. /**
  92430. * If the ray of the gaze should be displayed.
  92431. */
  92432. get: function () {
  92433. return this._displayGaze;
  92434. },
  92435. /**
  92436. * Sets if the ray of the gaze should be displayed.
  92437. */
  92438. set: function (value) {
  92439. this._displayGaze = value;
  92440. if (!value) {
  92441. this._cameraGazer._gazeTracker.isVisible = false;
  92442. if (this.leftController) {
  92443. this.leftController._gazeTracker.isVisible = false;
  92444. }
  92445. if (this.rightController) {
  92446. this.rightController._gazeTracker.isVisible = false;
  92447. }
  92448. }
  92449. },
  92450. enumerable: true,
  92451. configurable: true
  92452. });
  92453. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92454. /**
  92455. * If the ray of the LaserPointer should be displayed.
  92456. */
  92457. get: function () {
  92458. return this._displayLaserPointer;
  92459. },
  92460. /**
  92461. * Sets if the ray of the LaserPointer should be displayed.
  92462. */
  92463. set: function (value) {
  92464. this._displayLaserPointer = value;
  92465. if (!value) {
  92466. if (this.rightController) {
  92467. this.rightController._deactivatePointer();
  92468. this.rightController._gazeTracker.isVisible = false;
  92469. }
  92470. if (this.leftController) {
  92471. this.leftController._deactivatePointer();
  92472. this.leftController._gazeTracker.isVisible = false;
  92473. }
  92474. }
  92475. else {
  92476. if (this.rightController) {
  92477. this.rightController._activatePointer();
  92478. }
  92479. if (this.leftController) {
  92480. this.leftController._activatePointer();
  92481. }
  92482. }
  92483. },
  92484. enumerable: true,
  92485. configurable: true
  92486. });
  92487. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  92488. /**
  92489. * The deviceOrientationCamera used as the camera when not in VR.
  92490. */
  92491. get: function () {
  92492. return this._deviceOrientationCamera;
  92493. },
  92494. enumerable: true,
  92495. configurable: true
  92496. });
  92497. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  92498. /**
  92499. * Based on the current WebVR support, returns the current VR camera used.
  92500. */
  92501. get: function () {
  92502. if (this._webVRready) {
  92503. return this._webVRCamera;
  92504. }
  92505. else {
  92506. return this._scene.activeCamera;
  92507. }
  92508. },
  92509. enumerable: true,
  92510. configurable: true
  92511. });
  92512. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  92513. /**
  92514. * The webVRCamera which is used when in VR.
  92515. */
  92516. get: function () {
  92517. return this._webVRCamera;
  92518. },
  92519. enumerable: true,
  92520. configurable: true
  92521. });
  92522. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  92523. /**
  92524. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  92525. */
  92526. get: function () {
  92527. return this._vrDeviceOrientationCamera;
  92528. },
  92529. enumerable: true,
  92530. configurable: true
  92531. });
  92532. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  92533. get: function () {
  92534. var result = this._cameraGazer._teleportationRequestInitiated
  92535. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  92536. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  92537. return result;
  92538. },
  92539. enumerable: true,
  92540. configurable: true
  92541. });
  92542. // Raised when one of the controller has loaded successfully its associated default mesh
  92543. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  92544. if (this.leftController && this.leftController.webVRController == webVRController) {
  92545. if (webVRController.mesh) {
  92546. this.leftController._setLaserPointerParent(webVRController.mesh);
  92547. }
  92548. }
  92549. if (this.rightController && this.rightController.webVRController == webVRController) {
  92550. if (webVRController.mesh) {
  92551. this.rightController._setLaserPointerParent(webVRController.mesh);
  92552. }
  92553. }
  92554. try {
  92555. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  92556. }
  92557. catch (err) {
  92558. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  92559. }
  92560. };
  92561. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  92562. /**
  92563. * Gets a value indicating if we are currently in VR mode.
  92564. */
  92565. get: function () {
  92566. return this._webVRpresenting || this._fullscreenVRpresenting;
  92567. },
  92568. enumerable: true,
  92569. configurable: true
  92570. });
  92571. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  92572. var vrDisplay = this._scene.getEngine().getVRDevice();
  92573. if (vrDisplay) {
  92574. var wasPresenting = this._webVRpresenting;
  92575. // A VR display is connected
  92576. this._webVRpresenting = vrDisplay.isPresenting;
  92577. if (wasPresenting && !this._webVRpresenting)
  92578. this.exitVR();
  92579. }
  92580. else {
  92581. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  92582. }
  92583. this.updateButtonVisibility();
  92584. };
  92585. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  92586. this._webVRsupported = eventArgs.vrSupported;
  92587. this._webVRready = !!eventArgs.vrDisplay;
  92588. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  92589. this.updateButtonVisibility();
  92590. };
  92591. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  92592. if (this._canvas && !this._useCustomVRButton) {
  92593. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  92594. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  92595. }
  92596. };
  92597. VRExperienceHelper.prototype.displayVRButton = function () {
  92598. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  92599. document.body.appendChild(this._btnVR);
  92600. this._btnVRDisplayed = true;
  92601. }
  92602. };
  92603. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  92604. if (!this._btnVR || this._useCustomVRButton) {
  92605. return;
  92606. }
  92607. this._btnVR.className = "babylonVRicon";
  92608. if (this.isInVRMode) {
  92609. this._btnVR.className += " vrdisplaypresenting";
  92610. }
  92611. else {
  92612. if (this._webVRready)
  92613. this._btnVR.className += " vrdisplayready";
  92614. if (this._webVRsupported)
  92615. this._btnVR.className += " vrdisplaysupported";
  92616. if (this._webVRrequesting)
  92617. this._btnVR.className += " vrdisplayrequesting";
  92618. }
  92619. };
  92620. /**
  92621. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  92622. * Otherwise, will use the fullscreen API.
  92623. */
  92624. VRExperienceHelper.prototype.enterVR = function () {
  92625. if (this.onEnteringVRObservable) {
  92626. try {
  92627. this.onEnteringVRObservable.notifyObservers(this);
  92628. }
  92629. catch (err) {
  92630. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  92631. }
  92632. }
  92633. if (this._scene.activeCamera) {
  92634. this._position = this._scene.activeCamera.position.clone();
  92635. // make sure that we return to the last active camera
  92636. this._existingCamera = this._scene.activeCamera;
  92637. }
  92638. if (this._webVRrequesting)
  92639. return;
  92640. // If WebVR is supported and a headset is connected
  92641. if (this._webVRready) {
  92642. if (!this._webVRpresenting) {
  92643. this._webVRCamera.position = this._position;
  92644. this._scene.activeCamera = this._webVRCamera;
  92645. }
  92646. }
  92647. else if (this._vrDeviceOrientationCamera) {
  92648. this._vrDeviceOrientationCamera.position = this._position;
  92649. if (this._scene.activeCamera) {
  92650. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92651. }
  92652. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  92653. this._scene.getEngine().switchFullscreen(true);
  92654. this.updateButtonVisibility();
  92655. }
  92656. if (this._scene.activeCamera && this._canvas) {
  92657. this._scene.activeCamera.attachControl(this._canvas);
  92658. }
  92659. if (this._interactionsEnabled) {
  92660. this._scene.registerBeforeRender(this.beforeRender);
  92661. }
  92662. };
  92663. /**
  92664. * Attempt to exit VR, or fullscreen.
  92665. */
  92666. VRExperienceHelper.prototype.exitVR = function () {
  92667. if (this.onExitingVRObservable) {
  92668. try {
  92669. this.onExitingVRObservable.notifyObservers(this);
  92670. }
  92671. catch (err) {
  92672. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  92673. }
  92674. }
  92675. if (this._webVRpresenting) {
  92676. this._scene.getEngine().disableVR();
  92677. }
  92678. if (this._scene.activeCamera) {
  92679. this._position = this._scene.activeCamera.position.clone();
  92680. }
  92681. if (this._deviceOrientationCamera) {
  92682. this._deviceOrientationCamera.position = this._position;
  92683. this._scene.activeCamera = this._deviceOrientationCamera;
  92684. if (this._canvas) {
  92685. this._scene.activeCamera.attachControl(this._canvas);
  92686. }
  92687. }
  92688. else if (this._existingCamera) {
  92689. this._existingCamera.position = this._position;
  92690. this._scene.activeCamera = this._existingCamera;
  92691. }
  92692. this.updateButtonVisibility();
  92693. if (this._interactionsEnabled) {
  92694. this._scene.unregisterBeforeRender(this.beforeRender);
  92695. }
  92696. // resize to update width and height when exiting vr exits fullscreen
  92697. this._scene.getEngine().resize();
  92698. };
  92699. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  92700. /**
  92701. * The position of the vr experience helper.
  92702. */
  92703. get: function () {
  92704. return this._position;
  92705. },
  92706. /**
  92707. * Sets the position of the vr experience helper.
  92708. */
  92709. set: function (value) {
  92710. this._position = value;
  92711. if (this._scene.activeCamera) {
  92712. this._scene.activeCamera.position = value;
  92713. }
  92714. },
  92715. enumerable: true,
  92716. configurable: true
  92717. });
  92718. /**
  92719. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  92720. */
  92721. VRExperienceHelper.prototype.enableInteractions = function () {
  92722. var _this = this;
  92723. if (!this._interactionsEnabled) {
  92724. this._interactionsRequested = true;
  92725. if (this.leftController) {
  92726. this._enableInteractionOnController(this.leftController);
  92727. }
  92728. if (this.rightController) {
  92729. this._enableInteractionOnController(this.rightController);
  92730. }
  92731. this.raySelectionPredicate = function (mesh) {
  92732. return mesh.isVisible;
  92733. };
  92734. this.meshSelectionPredicate = function (mesh) {
  92735. return true;
  92736. };
  92737. this._raySelectionPredicate = function (mesh) {
  92738. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  92739. && mesh.name.indexOf("teleportationTarget") === -1
  92740. && mesh.name.indexOf("torusTeleportation") === -1
  92741. && mesh.name.indexOf("laserPointer") === -1)) {
  92742. return _this.raySelectionPredicate(mesh);
  92743. }
  92744. return false;
  92745. };
  92746. this._interactionsEnabled = true;
  92747. }
  92748. };
  92749. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  92750. get: function () {
  92751. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  92752. },
  92753. enumerable: true,
  92754. configurable: true
  92755. });
  92756. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  92757. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  92758. if (this._floorMeshesCollection[i].id === mesh.id) {
  92759. return true;
  92760. }
  92761. }
  92762. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  92763. return true;
  92764. }
  92765. return false;
  92766. };
  92767. /**
  92768. * Adds a floor mesh to be used for teleportation.
  92769. * @param floorMesh the mesh to be used for teleportation.
  92770. */
  92771. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  92772. if (!this._floorMeshesCollection) {
  92773. return;
  92774. }
  92775. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  92776. return;
  92777. }
  92778. this._floorMeshesCollection.push(floorMesh);
  92779. };
  92780. /**
  92781. * Removes a floor mesh from being used for teleportation.
  92782. * @param floorMesh the mesh to be removed.
  92783. */
  92784. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  92785. if (!this._floorMeshesCollection) {
  92786. return;
  92787. }
  92788. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  92789. if (meshIndex !== -1) {
  92790. this._floorMeshesCollection.splice(meshIndex, 1);
  92791. }
  92792. };
  92793. /**
  92794. * Enables interactions and teleportation using the VR controllers and gaze.
  92795. * @param vrTeleportationOptions options to modify teleportation behavior.
  92796. */
  92797. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  92798. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  92799. if (!this._teleportationInitialized) {
  92800. this._teleportationRequested = true;
  92801. this.enableInteractions();
  92802. if (vrTeleportationOptions.floorMeshName) {
  92803. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  92804. }
  92805. if (vrTeleportationOptions.floorMeshes) {
  92806. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  92807. }
  92808. if (this.leftController != null) {
  92809. this._enableTeleportationOnController(this.leftController);
  92810. }
  92811. if (this.rightController != null) {
  92812. this._enableTeleportationOnController(this.rightController);
  92813. }
  92814. // Creates an image processing post process for the vignette not relying
  92815. // on the main scene configuration for image processing to reduce setup and spaces
  92816. // (gamma/linear) conflicts.
  92817. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  92818. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  92819. imageProcessingConfiguration.vignetteEnabled = true;
  92820. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  92821. this._webVRCamera.detachPostProcess(this._postProcessMove);
  92822. this._teleportationInitialized = true;
  92823. if (this._isDefaultTeleportationTarget) {
  92824. this._createTeleportationCircles();
  92825. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  92826. }
  92827. }
  92828. };
  92829. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  92830. var _this = this;
  92831. var controllerMesh = controller.webVRController.mesh;
  92832. if (controllerMesh) {
  92833. controller._interactionsEnabled = true;
  92834. controller._activatePointer();
  92835. if (this.webVROptions.laserToggle) {
  92836. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  92837. // Enabling / disabling laserPointer
  92838. if (_this._displayLaserPointer && stateObject.value === 1) {
  92839. if (controller._activePointer) {
  92840. controller._deactivatePointer();
  92841. }
  92842. else {
  92843. controller._activatePointer();
  92844. }
  92845. if (_this.displayGaze) {
  92846. controller._gazeTracker.isVisible = controller._activePointer;
  92847. }
  92848. }
  92849. });
  92850. }
  92851. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  92852. var gazer = controller;
  92853. if (_this._noControllerIsActive) {
  92854. gazer = _this._cameraGazer;
  92855. }
  92856. if (!gazer._pointerDownOnMeshAsked) {
  92857. if (stateObject.value > _this._padSensibilityUp) {
  92858. gazer._selectionPointerDown();
  92859. }
  92860. }
  92861. else if (stateObject.value < _this._padSensibilityDown) {
  92862. gazer._selectionPointerUp();
  92863. }
  92864. });
  92865. }
  92866. };
  92867. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  92868. // Dont teleport if another gaze already requested teleportation
  92869. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  92870. return;
  92871. }
  92872. if (!gazer._teleportationRequestInitiated) {
  92873. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  92874. gazer._activatePointer();
  92875. gazer._teleportationRequestInitiated = true;
  92876. }
  92877. }
  92878. else {
  92879. // Listening to the proper controller values changes to confirm teleportation
  92880. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  92881. if (this._teleportActive) {
  92882. this._teleportCamera(this._haloCenter);
  92883. }
  92884. gazer._teleportationRequestInitiated = false;
  92885. }
  92886. }
  92887. };
  92888. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  92889. // Only rotate when user is not currently selecting a teleportation location
  92890. if (gazer._teleportationRequestInitiated) {
  92891. return;
  92892. }
  92893. if (!gazer._rotationLeftAsked) {
  92894. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  92895. gazer._rotationLeftAsked = true;
  92896. if (this._rotationAllowed) {
  92897. this._rotateCamera(false);
  92898. }
  92899. }
  92900. }
  92901. else {
  92902. if (stateObject.x > -this._padSensibilityDown) {
  92903. gazer._rotationLeftAsked = false;
  92904. }
  92905. }
  92906. if (!gazer._rotationRightAsked) {
  92907. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  92908. gazer._rotationRightAsked = true;
  92909. if (this._rotationAllowed) {
  92910. this._rotateCamera(true);
  92911. }
  92912. }
  92913. }
  92914. else {
  92915. if (stateObject.x < this._padSensibilityDown) {
  92916. gazer._rotationRightAsked = false;
  92917. }
  92918. }
  92919. };
  92920. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  92921. // Only teleport backwards when user is not currently selecting a teleportation location
  92922. if (gazer._teleportationRequestInitiated) {
  92923. return;
  92924. }
  92925. // Teleport backwards
  92926. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  92927. if (!gazer._teleportationBackRequestInitiated) {
  92928. if (!this.currentVRCamera) {
  92929. return;
  92930. }
  92931. // Get rotation and position of the current camera
  92932. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  92933. var position = this.currentVRCamera.position;
  92934. // If the camera has device position, use that instead
  92935. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  92936. rotation = this.currentVRCamera.deviceRotationQuaternion;
  92937. position = this.currentVRCamera.devicePosition;
  92938. }
  92939. // Get matrix with only the y rotation of the device rotation
  92940. rotation.toEulerAnglesToRef(this._workingVector);
  92941. this._workingVector.z = 0;
  92942. this._workingVector.x = 0;
  92943. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  92944. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  92945. // Rotate backwards ray by device rotation to cast at the ground behind the user
  92946. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  92947. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  92948. var ray = new BABYLON.Ray(position, this._workingVector);
  92949. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92950. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  92951. this._teleportCamera(hit.pickedPoint);
  92952. }
  92953. gazer._teleportationBackRequestInitiated = true;
  92954. }
  92955. }
  92956. else {
  92957. gazer._teleportationBackRequestInitiated = false;
  92958. }
  92959. };
  92960. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  92961. var _this = this;
  92962. var controllerMesh = controller.webVRController.mesh;
  92963. if (controllerMesh) {
  92964. if (!controller._interactionsEnabled) {
  92965. this._enableInteractionOnController(controller);
  92966. }
  92967. controller._interactionsEnabled = true;
  92968. controller._teleportationEnabled = true;
  92969. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92970. controller._dpadPressed = false;
  92971. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  92972. controller._dpadPressed = stateObject.pressed;
  92973. if (!controller._dpadPressed) {
  92974. controller._rotationLeftAsked = false;
  92975. controller._rotationRightAsked = false;
  92976. controller._teleportationBackRequestInitiated = false;
  92977. }
  92978. });
  92979. }
  92980. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  92981. if (_this.teleportationEnabled) {
  92982. _this._checkTeleportBackwards(stateObject, controller);
  92983. _this._checkTeleportWithRay(stateObject, controller);
  92984. }
  92985. _this._checkRotate(stateObject, controller);
  92986. });
  92987. }
  92988. };
  92989. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  92990. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  92991. this._teleportationTarget.isPickable = false;
  92992. var length = 512;
  92993. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  92994. dynamicTexture.hasAlpha = true;
  92995. var context = dynamicTexture.getContext();
  92996. var centerX = length / 2;
  92997. var centerY = length / 2;
  92998. var radius = 200;
  92999. context.beginPath();
  93000. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93001. context.fillStyle = this._teleportationFillColor;
  93002. context.fill();
  93003. context.lineWidth = 10;
  93004. context.strokeStyle = this._teleportationBorderColor;
  93005. context.stroke();
  93006. context.closePath();
  93007. dynamicTexture.update();
  93008. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93009. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93010. this._teleportationTarget.material = teleportationCircleMaterial;
  93011. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93012. torus.isPickable = false;
  93013. torus.parent = this._teleportationTarget;
  93014. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93015. var keys = [];
  93016. keys.push({
  93017. frame: 0,
  93018. value: 0
  93019. });
  93020. keys.push({
  93021. frame: 30,
  93022. value: 0.4
  93023. });
  93024. keys.push({
  93025. frame: 60,
  93026. value: 0
  93027. });
  93028. animationInnerCircle.setKeys(keys);
  93029. var easingFunction = new BABYLON.SineEase();
  93030. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93031. animationInnerCircle.setEasingFunction(easingFunction);
  93032. torus.animations = [];
  93033. torus.animations.push(animationInnerCircle);
  93034. this._scene.beginAnimation(torus, 0, 60, true);
  93035. this._hideTeleportationTarget();
  93036. };
  93037. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93038. this._teleportActive = true;
  93039. if (this._teleportationInitialized) {
  93040. this._teleportationTarget.isVisible = true;
  93041. if (this._isDefaultTeleportationTarget) {
  93042. this._teleportationTarget.getChildren()[0].isVisible = true;
  93043. }
  93044. }
  93045. };
  93046. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93047. this._teleportActive = false;
  93048. if (this._teleportationInitialized) {
  93049. this._teleportationTarget.isVisible = false;
  93050. if (this._isDefaultTeleportationTarget) {
  93051. this._teleportationTarget.getChildren()[0].isVisible = false;
  93052. }
  93053. }
  93054. };
  93055. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93056. var _this = this;
  93057. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93058. return;
  93059. }
  93060. if (right) {
  93061. this._rotationAngle++;
  93062. }
  93063. else {
  93064. this._rotationAngle--;
  93065. }
  93066. this.currentVRCamera.animations = [];
  93067. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93068. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93069. var animationRotationKeys = [];
  93070. animationRotationKeys.push({
  93071. frame: 0,
  93072. value: this.currentVRCamera.rotationQuaternion
  93073. });
  93074. animationRotationKeys.push({
  93075. frame: 6,
  93076. value: target
  93077. });
  93078. animationRotation.setKeys(animationRotationKeys);
  93079. animationRotation.setEasingFunction(this._circleEase);
  93080. this.currentVRCamera.animations.push(animationRotation);
  93081. this._postProcessMove.animations = [];
  93082. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93083. var vignetteWeightKeys = [];
  93084. vignetteWeightKeys.push({
  93085. frame: 0,
  93086. value: 0
  93087. });
  93088. vignetteWeightKeys.push({
  93089. frame: 3,
  93090. value: 4
  93091. });
  93092. vignetteWeightKeys.push({
  93093. frame: 6,
  93094. value: 0
  93095. });
  93096. animationPP.setKeys(vignetteWeightKeys);
  93097. animationPP.setEasingFunction(this._circleEase);
  93098. this._postProcessMove.animations.push(animationPP);
  93099. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93100. var vignetteStretchKeys = [];
  93101. vignetteStretchKeys.push({
  93102. frame: 0,
  93103. value: 0
  93104. });
  93105. vignetteStretchKeys.push({
  93106. frame: 3,
  93107. value: 10
  93108. });
  93109. vignetteStretchKeys.push({
  93110. frame: 6,
  93111. value: 0
  93112. });
  93113. animationPP2.setKeys(vignetteStretchKeys);
  93114. animationPP2.setEasingFunction(this._circleEase);
  93115. this._postProcessMove.animations.push(animationPP2);
  93116. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93117. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93118. this._postProcessMove.samples = 4;
  93119. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93120. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93121. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93122. });
  93123. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93124. };
  93125. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93126. if (hit.pickedPoint) {
  93127. if (gazer._teleportationRequestInitiated) {
  93128. this._displayTeleportationTarget();
  93129. this._haloCenter.copyFrom(hit.pickedPoint);
  93130. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93131. }
  93132. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93133. if (pickNormal) {
  93134. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93135. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93136. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93137. }
  93138. this._teleportationTarget.position.y += 0.1;
  93139. }
  93140. };
  93141. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93142. var _this = this;
  93143. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93144. return;
  93145. }
  93146. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93147. // offset of the headset from the anchor.
  93148. if (this.webVRCamera.leftCamera) {
  93149. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93150. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93151. location.subtractToRef(this._workingVector, this._workingVector);
  93152. }
  93153. else {
  93154. this._workingVector.copyFrom(location);
  93155. }
  93156. // Add height to account for user's height offset
  93157. if (this.isInVRMode) {
  93158. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93159. }
  93160. else {
  93161. this._workingVector.y += this._defaultHeight;
  93162. }
  93163. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93164. // Create animation from the camera's position to the new location
  93165. this.currentVRCamera.animations = [];
  93166. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93167. var animationCameraTeleportationKeys = [{
  93168. frame: 0,
  93169. value: this.currentVRCamera.position
  93170. },
  93171. {
  93172. frame: 11,
  93173. value: this._workingVector
  93174. }
  93175. ];
  93176. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93177. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93178. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93179. this._postProcessMove.animations = [];
  93180. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93181. var vignetteWeightKeys = [];
  93182. vignetteWeightKeys.push({
  93183. frame: 0,
  93184. value: 0
  93185. });
  93186. vignetteWeightKeys.push({
  93187. frame: 5,
  93188. value: 8
  93189. });
  93190. vignetteWeightKeys.push({
  93191. frame: 11,
  93192. value: 0
  93193. });
  93194. animationPP.setKeys(vignetteWeightKeys);
  93195. this._postProcessMove.animations.push(animationPP);
  93196. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93197. var vignetteStretchKeys = [];
  93198. vignetteStretchKeys.push({
  93199. frame: 0,
  93200. value: 0
  93201. });
  93202. vignetteStretchKeys.push({
  93203. frame: 5,
  93204. value: 10
  93205. });
  93206. vignetteStretchKeys.push({
  93207. frame: 11,
  93208. value: 0
  93209. });
  93210. animationPP2.setKeys(vignetteStretchKeys);
  93211. this._postProcessMove.animations.push(animationPP2);
  93212. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93213. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93214. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93215. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93216. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93217. });
  93218. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93219. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93220. });
  93221. this._hideTeleportationTarget();
  93222. };
  93223. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93224. if (normal) {
  93225. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93226. if (angle < Math.PI / 2) {
  93227. normal.scaleInPlace(-1);
  93228. }
  93229. }
  93230. return normal;
  93231. };
  93232. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93233. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93234. return;
  93235. }
  93236. var ray = gazer._getForwardRay(this._rayLength);
  93237. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93238. if (hit) {
  93239. // Populate the contrllers mesh that can be used for drag/drop
  93240. if (gazer._laserPointer) {
  93241. hit.originMesh = gazer._laserPointer.parent;
  93242. }
  93243. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93244. }
  93245. gazer._currentHit = hit;
  93246. // Moving the gazeTracker on the mesh face targetted
  93247. if (hit && hit.pickedPoint) {
  93248. if (this._displayGaze) {
  93249. var multiplier = 1;
  93250. gazer._gazeTracker.isVisible = true;
  93251. if (gazer._isActionableMesh) {
  93252. multiplier = 3;
  93253. }
  93254. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93255. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93256. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93257. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93258. // To avoid z-fighting
  93259. var deltaFighting = 0.002;
  93260. if (pickNormal) {
  93261. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93262. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93263. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93264. }
  93265. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93266. if (gazer._gazeTracker.position.x < 0) {
  93267. gazer._gazeTracker.position.x += deltaFighting;
  93268. }
  93269. else {
  93270. gazer._gazeTracker.position.x -= deltaFighting;
  93271. }
  93272. if (gazer._gazeTracker.position.y < 0) {
  93273. gazer._gazeTracker.position.y += deltaFighting;
  93274. }
  93275. else {
  93276. gazer._gazeTracker.position.y -= deltaFighting;
  93277. }
  93278. if (gazer._gazeTracker.position.z < 0) {
  93279. gazer._gazeTracker.position.z += deltaFighting;
  93280. }
  93281. else {
  93282. gazer._gazeTracker.position.z -= deltaFighting;
  93283. }
  93284. }
  93285. // Changing the size of the laser pointer based on the distance from the targetted point
  93286. gazer._updatePointerDistance(hit.distance);
  93287. }
  93288. else {
  93289. gazer._updatePointerDistance();
  93290. gazer._gazeTracker.isVisible = false;
  93291. }
  93292. if (hit && hit.pickedMesh) {
  93293. // The object selected is the floor, we're in a teleportation scenario
  93294. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93295. // Moving the teleportation area to this targetted point
  93296. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93297. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93298. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93299. }
  93300. gazer._currentMeshSelected = null;
  93301. if (gazer._teleportationRequestInitiated) {
  93302. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93303. }
  93304. return;
  93305. }
  93306. // If not, we're in a selection scenario
  93307. //this._teleportationAllowed = false;
  93308. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93309. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93310. this.onNewMeshPicked.notifyObservers(hit);
  93311. gazer._currentMeshSelected = hit.pickedMesh;
  93312. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93313. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93314. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93315. gazer._isActionableMesh = true;
  93316. }
  93317. else {
  93318. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93319. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93320. gazer._isActionableMesh = false;
  93321. }
  93322. try {
  93323. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93324. }
  93325. catch (err) {
  93326. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93327. }
  93328. }
  93329. else {
  93330. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93331. gazer._currentMeshSelected = null;
  93332. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93333. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93334. }
  93335. }
  93336. }
  93337. else {
  93338. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93339. gazer._currentMeshSelected = null;
  93340. //this._teleportationAllowed = false;
  93341. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93342. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93343. }
  93344. };
  93345. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93346. if (mesh) {
  93347. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93348. }
  93349. };
  93350. /**
  93351. * Sets the color of the laser ray from the vr controllers.
  93352. * @param color new color for the ray.
  93353. */
  93354. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93355. if (this.leftController) {
  93356. this.leftController._setLaserPointerColor(color);
  93357. }
  93358. if (this.rightController) {
  93359. this.rightController._setLaserPointerColor(color);
  93360. }
  93361. };
  93362. /**
  93363. * Sets the color of the ray from the vr headsets gaze.
  93364. * @param color new color for the ray.
  93365. */
  93366. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93367. if (!this._cameraGazer._gazeTracker.material) {
  93368. return;
  93369. }
  93370. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93371. if (this.leftController) {
  93372. this.leftController._gazeTracker.material.emissiveColor = color;
  93373. }
  93374. if (this.rightController) {
  93375. this.rightController._gazeTracker.material.emissiveColor = color;
  93376. }
  93377. };
  93378. /**
  93379. * Exits VR and disposes of the vr experience helper
  93380. */
  93381. VRExperienceHelper.prototype.dispose = function () {
  93382. if (this.isInVRMode) {
  93383. this.exitVR();
  93384. }
  93385. if (this._postProcessMove) {
  93386. this._postProcessMove.dispose();
  93387. }
  93388. if (this._webVRCamera) {
  93389. this._webVRCamera.dispose();
  93390. }
  93391. if (this._vrDeviceOrientationCamera) {
  93392. this._vrDeviceOrientationCamera.dispose();
  93393. }
  93394. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93395. document.body.removeChild(this._btnVR);
  93396. }
  93397. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93398. this._deviceOrientationCamera.dispose();
  93399. }
  93400. if (this._cameraGazer) {
  93401. this._cameraGazer.dispose();
  93402. }
  93403. if (this.leftController) {
  93404. this.leftController.dispose();
  93405. }
  93406. if (this.rightController) {
  93407. this.rightController.dispose();
  93408. }
  93409. if (this._teleportationTarget) {
  93410. this._teleportationTarget.dispose();
  93411. }
  93412. this._floorMeshesCollection = [];
  93413. document.removeEventListener("keydown", this._onKeyDown);
  93414. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93415. window.removeEventListener("resize", this._onResize);
  93416. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93417. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93418. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93419. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93420. document.onmsfullscreenchange = null;
  93421. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93422. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93423. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93424. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93425. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93426. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93427. this._scene.unregisterBeforeRender(this.beforeRender);
  93428. };
  93429. /**
  93430. * Gets the name of the VRExperienceHelper class
  93431. * @returns "VRExperienceHelper"
  93432. */
  93433. VRExperienceHelper.prototype.getClassName = function () {
  93434. return "VRExperienceHelper";
  93435. };
  93436. return VRExperienceHelper;
  93437. }());
  93438. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93439. })(BABYLON || (BABYLON = {}));
  93440. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93441. // Mainly based on these 2 articles :
  93442. // 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
  93443. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93444. var BABYLON;
  93445. (function (BABYLON) {
  93446. /**
  93447. * Defines the potential axis of a Joystick
  93448. */
  93449. var JoystickAxis;
  93450. (function (JoystickAxis) {
  93451. /** X axis */
  93452. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93453. /** Y axis */
  93454. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93455. /** Z axis */
  93456. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93457. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93458. /**
  93459. * Class used to define virtual joystick (used in touch mode)
  93460. */
  93461. var VirtualJoystick = /** @class */ (function () {
  93462. /**
  93463. * Creates a new virtual joystick
  93464. * @param leftJoystick defines that the joystick is for left hand (false by default)
  93465. */
  93466. function VirtualJoystick(leftJoystick) {
  93467. var _this = this;
  93468. if (leftJoystick) {
  93469. this._leftJoystick = true;
  93470. }
  93471. else {
  93472. this._leftJoystick = false;
  93473. }
  93474. VirtualJoystick._globalJoystickIndex++;
  93475. // By default left & right arrow keys are moving the X
  93476. // and up & down keys are moving the Y
  93477. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93478. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93479. this.reverseLeftRight = false;
  93480. this.reverseUpDown = false;
  93481. // collections of pointers
  93482. this._touches = new BABYLON.StringDictionary();
  93483. this.deltaPosition = BABYLON.Vector3.Zero();
  93484. this._joystickSensibility = 25;
  93485. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93486. this._onResize = function (evt) {
  93487. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93488. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93489. if (VirtualJoystick.vjCanvas) {
  93490. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  93491. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  93492. }
  93493. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  93494. };
  93495. // injecting a canvas element on top of the canvas 3D game
  93496. if (!VirtualJoystick.vjCanvas) {
  93497. window.addEventListener("resize", this._onResize, false);
  93498. VirtualJoystick.vjCanvas = document.createElement("canvas");
  93499. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93500. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93501. VirtualJoystick.vjCanvas.width = window.innerWidth;
  93502. VirtualJoystick.vjCanvas.height = window.innerHeight;
  93503. VirtualJoystick.vjCanvas.style.width = "100%";
  93504. VirtualJoystick.vjCanvas.style.height = "100%";
  93505. VirtualJoystick.vjCanvas.style.position = "absolute";
  93506. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  93507. VirtualJoystick.vjCanvas.style.top = "0px";
  93508. VirtualJoystick.vjCanvas.style.left = "0px";
  93509. VirtualJoystick.vjCanvas.style.zIndex = "5";
  93510. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  93511. // Support for jQuery PEP polyfill
  93512. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  93513. var context = VirtualJoystick.vjCanvas.getContext('2d');
  93514. if (!context) {
  93515. throw new Error("Unable to create canvas for virtual joystick");
  93516. }
  93517. VirtualJoystick.vjCanvasContext = context;
  93518. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  93519. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93520. document.body.appendChild(VirtualJoystick.vjCanvas);
  93521. }
  93522. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  93523. this.pressed = false;
  93524. // default joystick color
  93525. this._joystickColor = "cyan";
  93526. this._joystickPointerID = -1;
  93527. // current joystick position
  93528. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  93529. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  93530. // origin joystick position
  93531. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  93532. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  93533. this._onPointerDownHandlerRef = function (evt) {
  93534. _this._onPointerDown(evt);
  93535. };
  93536. this._onPointerMoveHandlerRef = function (evt) {
  93537. _this._onPointerMove(evt);
  93538. };
  93539. this._onPointerUpHandlerRef = function (evt) {
  93540. _this._onPointerUp(evt);
  93541. };
  93542. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  93543. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  93544. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  93545. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  93546. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  93547. evt.preventDefault(); // Disables system menu
  93548. }, false);
  93549. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93550. }
  93551. /**
  93552. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  93553. * @param newJoystickSensibility defines the new sensibility
  93554. */
  93555. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  93556. this._joystickSensibility = newJoystickSensibility;
  93557. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93558. };
  93559. VirtualJoystick.prototype._onPointerDown = function (e) {
  93560. var positionOnScreenCondition;
  93561. e.preventDefault();
  93562. if (this._leftJoystick === true) {
  93563. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  93564. }
  93565. else {
  93566. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  93567. }
  93568. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  93569. // First contact will be dedicated to the virtual joystick
  93570. this._joystickPointerID = e.pointerId;
  93571. this._joystickPointerStartPos.x = e.clientX;
  93572. this._joystickPointerStartPos.y = e.clientY;
  93573. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  93574. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  93575. this._deltaJoystickVector.x = 0;
  93576. this._deltaJoystickVector.y = 0;
  93577. this.pressed = true;
  93578. this._touches.add(e.pointerId.toString(), e);
  93579. }
  93580. else {
  93581. // You can only trigger the action buttons with a joystick declared
  93582. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  93583. this._action();
  93584. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  93585. }
  93586. }
  93587. };
  93588. VirtualJoystick.prototype._onPointerMove = function (e) {
  93589. // If the current pointer is the one associated to the joystick (first touch contact)
  93590. if (this._joystickPointerID == e.pointerId) {
  93591. this._joystickPointerPos.x = e.clientX;
  93592. this._joystickPointerPos.y = e.clientY;
  93593. this._deltaJoystickVector = this._joystickPointerPos.clone();
  93594. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  93595. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  93596. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  93597. switch (this._axisTargetedByLeftAndRight) {
  93598. case JoystickAxis.X:
  93599. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  93600. break;
  93601. case JoystickAxis.Y:
  93602. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  93603. break;
  93604. case JoystickAxis.Z:
  93605. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  93606. break;
  93607. }
  93608. var directionUpDown = this.reverseUpDown ? 1 : -1;
  93609. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  93610. switch (this._axisTargetedByUpAndDown) {
  93611. case JoystickAxis.X:
  93612. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  93613. break;
  93614. case JoystickAxis.Y:
  93615. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  93616. break;
  93617. case JoystickAxis.Z:
  93618. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  93619. break;
  93620. }
  93621. }
  93622. else {
  93623. var data = this._touches.get(e.pointerId.toString());
  93624. if (data) {
  93625. data.x = e.clientX;
  93626. data.y = e.clientY;
  93627. }
  93628. }
  93629. };
  93630. VirtualJoystick.prototype._onPointerUp = function (e) {
  93631. if (this._joystickPointerID == e.pointerId) {
  93632. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  93633. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  93634. this._joystickPointerID = -1;
  93635. this.pressed = false;
  93636. }
  93637. else {
  93638. var touch = this._touches.get(e.pointerId.toString());
  93639. if (touch) {
  93640. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93641. }
  93642. }
  93643. this._deltaJoystickVector.x = 0;
  93644. this._deltaJoystickVector.y = 0;
  93645. this._touches.remove(e.pointerId.toString());
  93646. };
  93647. /**
  93648. * Change the color of the virtual joystick
  93649. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  93650. */
  93651. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  93652. this._joystickColor = newColor;
  93653. };
  93654. /**
  93655. * Defines a callback to call when the joystick is touched
  93656. * @param action defines the callback
  93657. */
  93658. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  93659. this._action = action;
  93660. };
  93661. /**
  93662. * Defines which axis you'd like to control for left & right
  93663. * @param axis defines the axis to use
  93664. */
  93665. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  93666. switch (axis) {
  93667. case JoystickAxis.X:
  93668. case JoystickAxis.Y:
  93669. case JoystickAxis.Z:
  93670. this._axisTargetedByLeftAndRight = axis;
  93671. break;
  93672. default:
  93673. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93674. break;
  93675. }
  93676. };
  93677. /**
  93678. * Defines which axis you'd like to control for up & down
  93679. * @param axis defines the axis to use
  93680. */
  93681. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  93682. switch (axis) {
  93683. case JoystickAxis.X:
  93684. case JoystickAxis.Y:
  93685. case JoystickAxis.Z:
  93686. this._axisTargetedByUpAndDown = axis;
  93687. break;
  93688. default:
  93689. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93690. break;
  93691. }
  93692. };
  93693. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  93694. var _this = this;
  93695. if (this.pressed) {
  93696. this._touches.forEach(function (key, touch) {
  93697. if (touch.pointerId === _this._joystickPointerID) {
  93698. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  93699. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  93700. VirtualJoystick.vjCanvasContext.beginPath();
  93701. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93702. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93703. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  93704. VirtualJoystick.vjCanvasContext.stroke();
  93705. VirtualJoystick.vjCanvasContext.closePath();
  93706. VirtualJoystick.vjCanvasContext.beginPath();
  93707. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93708. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93709. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  93710. VirtualJoystick.vjCanvasContext.stroke();
  93711. VirtualJoystick.vjCanvasContext.closePath();
  93712. VirtualJoystick.vjCanvasContext.beginPath();
  93713. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93714. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  93715. VirtualJoystick.vjCanvasContext.stroke();
  93716. VirtualJoystick.vjCanvasContext.closePath();
  93717. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  93718. }
  93719. else {
  93720. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93721. VirtualJoystick.vjCanvasContext.beginPath();
  93722. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  93723. VirtualJoystick.vjCanvasContext.beginPath();
  93724. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  93725. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93726. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  93727. VirtualJoystick.vjCanvasContext.stroke();
  93728. VirtualJoystick.vjCanvasContext.closePath();
  93729. touch.prevX = touch.x;
  93730. touch.prevY = touch.y;
  93731. }
  93732. ;
  93733. });
  93734. }
  93735. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93736. };
  93737. /**
  93738. * Release internal HTML canvas
  93739. */
  93740. VirtualJoystick.prototype.releaseCanvas = function () {
  93741. if (VirtualJoystick.vjCanvas) {
  93742. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  93743. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  93744. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  93745. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  93746. window.removeEventListener("resize", this._onResize);
  93747. document.body.removeChild(VirtualJoystick.vjCanvas);
  93748. VirtualJoystick.vjCanvas = null;
  93749. }
  93750. };
  93751. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  93752. VirtualJoystick._globalJoystickIndex = 0;
  93753. return VirtualJoystick;
  93754. }());
  93755. BABYLON.VirtualJoystick = VirtualJoystick;
  93756. })(BABYLON || (BABYLON = {}));
  93757. //# sourceMappingURL=babylon.virtualJoystick.js.map
  93758. var BABYLON;
  93759. (function (BABYLON) {
  93760. // We're mainly based on the logic defined into the FreeCamera code
  93761. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  93762. __extends(VirtualJoysticksCamera, _super);
  93763. function VirtualJoysticksCamera(name, position, scene) {
  93764. var _this = _super.call(this, name, position, scene) || this;
  93765. _this.inputs.addVirtualJoystick();
  93766. return _this;
  93767. }
  93768. VirtualJoysticksCamera.prototype.getClassName = function () {
  93769. return "VirtualJoysticksCamera";
  93770. };
  93771. return VirtualJoysticksCamera;
  93772. }(BABYLON.FreeCamera));
  93773. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  93774. })(BABYLON || (BABYLON = {}));
  93775. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  93776. var BABYLON;
  93777. (function (BABYLON) {
  93778. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  93779. function FreeCameraVirtualJoystickInput() {
  93780. }
  93781. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  93782. return this._leftjoystick;
  93783. };
  93784. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  93785. return this._rightjoystick;
  93786. };
  93787. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  93788. if (this._leftjoystick) {
  93789. var camera = this.camera;
  93790. var speed = camera._computeLocalCameraSpeed() * 50;
  93791. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  93792. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  93793. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  93794. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  93795. if (!this._leftjoystick.pressed) {
  93796. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  93797. }
  93798. if (!this._rightjoystick.pressed) {
  93799. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  93800. }
  93801. }
  93802. };
  93803. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  93804. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  93805. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  93806. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  93807. this._leftjoystick.setJoystickSensibility(0.15);
  93808. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  93809. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  93810. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  93811. this._rightjoystick.reverseUpDown = true;
  93812. this._rightjoystick.setJoystickSensibility(0.05);
  93813. this._rightjoystick.setJoystickColor("yellow");
  93814. };
  93815. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  93816. this._leftjoystick.releaseCanvas();
  93817. this._rightjoystick.releaseCanvas();
  93818. };
  93819. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  93820. return "FreeCameraVirtualJoystickInput";
  93821. };
  93822. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  93823. return "virtualJoystick";
  93824. };
  93825. return FreeCameraVirtualJoystickInput;
  93826. }());
  93827. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  93828. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  93829. })(BABYLON || (BABYLON = {}));
  93830. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  93831. var BABYLON;
  93832. (function (BABYLON) {
  93833. var SimplificationSettings = /** @class */ (function () {
  93834. function SimplificationSettings(quality, distance, optimizeMesh) {
  93835. this.quality = quality;
  93836. this.distance = distance;
  93837. this.optimizeMesh = optimizeMesh;
  93838. }
  93839. return SimplificationSettings;
  93840. }());
  93841. BABYLON.SimplificationSettings = SimplificationSettings;
  93842. var SimplificationQueue = /** @class */ (function () {
  93843. function SimplificationQueue() {
  93844. this.running = false;
  93845. this._simplificationArray = [];
  93846. }
  93847. SimplificationQueue.prototype.addTask = function (task) {
  93848. this._simplificationArray.push(task);
  93849. };
  93850. SimplificationQueue.prototype.executeNext = function () {
  93851. var task = this._simplificationArray.pop();
  93852. if (task) {
  93853. this.running = true;
  93854. this.runSimplification(task);
  93855. }
  93856. else {
  93857. this.running = false;
  93858. }
  93859. };
  93860. SimplificationQueue.prototype.runSimplification = function (task) {
  93861. var _this = this;
  93862. if (task.parallelProcessing) {
  93863. //parallel simplifier
  93864. task.settings.forEach(function (setting) {
  93865. var simplifier = _this.getSimplifier(task);
  93866. simplifier.simplify(setting, function (newMesh) {
  93867. task.mesh.addLODLevel(setting.distance, newMesh);
  93868. newMesh.isVisible = true;
  93869. //check if it is the last
  93870. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  93871. //all done, run the success callback.
  93872. task.successCallback();
  93873. }
  93874. _this.executeNext();
  93875. });
  93876. });
  93877. }
  93878. else {
  93879. //single simplifier.
  93880. var simplifier = this.getSimplifier(task);
  93881. var runDecimation = function (setting, callback) {
  93882. simplifier.simplify(setting, function (newMesh) {
  93883. task.mesh.addLODLevel(setting.distance, newMesh);
  93884. newMesh.isVisible = true;
  93885. //run the next quality level
  93886. callback();
  93887. });
  93888. };
  93889. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  93890. runDecimation(task.settings[loop.index], function () {
  93891. loop.executeNext();
  93892. });
  93893. }, function () {
  93894. //execution ended, run the success callback.
  93895. if (task.successCallback) {
  93896. task.successCallback();
  93897. }
  93898. _this.executeNext();
  93899. });
  93900. }
  93901. };
  93902. SimplificationQueue.prototype.getSimplifier = function (task) {
  93903. switch (task.simplificationType) {
  93904. case SimplificationType.QUADRATIC:
  93905. default:
  93906. return new QuadraticErrorSimplification(task.mesh);
  93907. }
  93908. };
  93909. return SimplificationQueue;
  93910. }());
  93911. BABYLON.SimplificationQueue = SimplificationQueue;
  93912. /**
  93913. * The implemented types of simplification
  93914. * At the moment only Quadratic Error Decimation is implemented
  93915. */
  93916. var SimplificationType;
  93917. (function (SimplificationType) {
  93918. /** Quadratic error decimation */
  93919. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  93920. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  93921. var DecimationTriangle = /** @class */ (function () {
  93922. function DecimationTriangle(vertices) {
  93923. this.vertices = vertices;
  93924. this.error = new Array(4);
  93925. this.deleted = false;
  93926. this.isDirty = false;
  93927. this.deletePending = false;
  93928. this.borderFactor = 0;
  93929. }
  93930. return DecimationTriangle;
  93931. }());
  93932. BABYLON.DecimationTriangle = DecimationTriangle;
  93933. var DecimationVertex = /** @class */ (function () {
  93934. function DecimationVertex(position, id) {
  93935. this.position = position;
  93936. this.id = id;
  93937. this.isBorder = true;
  93938. this.q = new QuadraticMatrix();
  93939. this.triangleCount = 0;
  93940. this.triangleStart = 0;
  93941. this.originalOffsets = [];
  93942. }
  93943. DecimationVertex.prototype.updatePosition = function (newPosition) {
  93944. this.position.copyFrom(newPosition);
  93945. };
  93946. return DecimationVertex;
  93947. }());
  93948. BABYLON.DecimationVertex = DecimationVertex;
  93949. var QuadraticMatrix = /** @class */ (function () {
  93950. function QuadraticMatrix(data) {
  93951. this.data = new Array(10);
  93952. for (var i = 0; i < 10; ++i) {
  93953. if (data && data[i]) {
  93954. this.data[i] = data[i];
  93955. }
  93956. else {
  93957. this.data[i] = 0;
  93958. }
  93959. }
  93960. }
  93961. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  93962. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  93963. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  93964. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  93965. return det;
  93966. };
  93967. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  93968. for (var i = 0; i < 10; ++i) {
  93969. this.data[i] += matrix.data[i];
  93970. }
  93971. };
  93972. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  93973. for (var i = 0; i < 10; ++i) {
  93974. this.data[i] += data[i];
  93975. }
  93976. };
  93977. QuadraticMatrix.prototype.add = function (matrix) {
  93978. var m = new QuadraticMatrix();
  93979. for (var i = 0; i < 10; ++i) {
  93980. m.data[i] = this.data[i] + matrix.data[i];
  93981. }
  93982. return m;
  93983. };
  93984. QuadraticMatrix.FromData = function (a, b, c, d) {
  93985. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  93986. };
  93987. //returning an array to avoid garbage collection
  93988. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  93989. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  93990. };
  93991. return QuadraticMatrix;
  93992. }());
  93993. BABYLON.QuadraticMatrix = QuadraticMatrix;
  93994. var Reference = /** @class */ (function () {
  93995. function Reference(vertexId, triangleId) {
  93996. this.vertexId = vertexId;
  93997. this.triangleId = triangleId;
  93998. }
  93999. return Reference;
  94000. }());
  94001. BABYLON.Reference = Reference;
  94002. /**
  94003. * An implementation of the Quadratic Error simplification algorithm.
  94004. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94005. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94006. * @author RaananW
  94007. */
  94008. var QuadraticErrorSimplification = /** @class */ (function () {
  94009. function QuadraticErrorSimplification(_mesh) {
  94010. this._mesh = _mesh;
  94011. this.syncIterations = 5000;
  94012. this.aggressiveness = 7;
  94013. this.decimationIterations = 100;
  94014. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94015. }
  94016. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94017. var _this = this;
  94018. this.initDecimatedMesh();
  94019. //iterating through the submeshes array, one after the other.
  94020. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94021. _this.initWithMesh(loop.index, function () {
  94022. _this.runDecimation(settings, loop.index, function () {
  94023. loop.executeNext();
  94024. });
  94025. }, settings.optimizeMesh);
  94026. }, function () {
  94027. setTimeout(function () {
  94028. successCallback(_this._reconstructedMesh);
  94029. }, 0);
  94030. });
  94031. };
  94032. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94033. var _this = this;
  94034. var targetCount = ~~(this.triangles.length * settings.quality);
  94035. var deletedTriangles = 0;
  94036. var triangleCount = this.triangles.length;
  94037. var iterationFunction = function (iteration, callback) {
  94038. setTimeout(function () {
  94039. if (iteration % 5 === 0) {
  94040. _this.updateMesh(iteration === 0);
  94041. }
  94042. for (var i = 0; i < _this.triangles.length; ++i) {
  94043. _this.triangles[i].isDirty = false;
  94044. }
  94045. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94046. var trianglesIterator = function (i) {
  94047. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94048. var t = _this.triangles[tIdx];
  94049. if (!t)
  94050. return;
  94051. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94052. return;
  94053. }
  94054. for (var j = 0; j < 3; ++j) {
  94055. if (t.error[j] < threshold) {
  94056. var deleted0 = [];
  94057. var deleted1 = [];
  94058. var v0 = t.vertices[j];
  94059. var v1 = t.vertices[(j + 1) % 3];
  94060. if (v0.isBorder || v1.isBorder)
  94061. continue;
  94062. var p = BABYLON.Vector3.Zero();
  94063. var n = BABYLON.Vector3.Zero();
  94064. var uv = BABYLON.Vector2.Zero();
  94065. var color = new BABYLON.Color4(0, 0, 0, 1);
  94066. _this.calculateError(v0, v1, p, n, uv, color);
  94067. var delTr = new Array();
  94068. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94069. continue;
  94070. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94071. continue;
  94072. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94073. continue;
  94074. var uniqueArray = new Array();
  94075. delTr.forEach(function (deletedT) {
  94076. if (uniqueArray.indexOf(deletedT) === -1) {
  94077. deletedT.deletePending = true;
  94078. uniqueArray.push(deletedT);
  94079. }
  94080. });
  94081. if (uniqueArray.length % 2 !== 0) {
  94082. continue;
  94083. }
  94084. v0.q = v1.q.add(v0.q);
  94085. v0.updatePosition(p);
  94086. var tStart = _this.references.length;
  94087. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94088. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94089. var tCount = _this.references.length - tStart;
  94090. if (tCount <= v0.triangleCount) {
  94091. if (tCount) {
  94092. for (var c = 0; c < tCount; c++) {
  94093. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94094. }
  94095. }
  94096. }
  94097. else {
  94098. v0.triangleStart = tStart;
  94099. }
  94100. v0.triangleCount = tCount;
  94101. break;
  94102. }
  94103. }
  94104. };
  94105. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94106. }, 0);
  94107. };
  94108. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94109. if (triangleCount - deletedTriangles <= targetCount)
  94110. loop.breakLoop();
  94111. else {
  94112. iterationFunction(loop.index, function () {
  94113. loop.executeNext();
  94114. });
  94115. }
  94116. }, function () {
  94117. setTimeout(function () {
  94118. //reconstruct this part of the mesh
  94119. _this.reconstructMesh(submeshIndex);
  94120. successCallback();
  94121. }, 0);
  94122. });
  94123. };
  94124. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94125. var _this = this;
  94126. this.vertices = [];
  94127. this.triangles = [];
  94128. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94129. var indices = this._mesh.getIndices();
  94130. var submesh = this._mesh.subMeshes[submeshIndex];
  94131. var findInVertices = function (positionToSearch) {
  94132. if (optimizeMesh) {
  94133. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94134. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94135. return _this.vertices[ii];
  94136. }
  94137. }
  94138. }
  94139. return null;
  94140. };
  94141. var vertexReferences = [];
  94142. var vertexInit = function (i) {
  94143. if (!positionData) {
  94144. return;
  94145. }
  94146. var offset = i + submesh.verticesStart;
  94147. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94148. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94149. vertex.originalOffsets.push(offset);
  94150. if (vertex.id === _this.vertices.length) {
  94151. _this.vertices.push(vertex);
  94152. }
  94153. vertexReferences.push(vertex.id);
  94154. };
  94155. //var totalVertices = mesh.getTotalVertices();
  94156. var totalVertices = submesh.verticesCount;
  94157. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94158. var indicesInit = function (i) {
  94159. if (!indices) {
  94160. return;
  94161. }
  94162. var offset = (submesh.indexStart / 3) + i;
  94163. var pos = (offset * 3);
  94164. var i0 = indices[pos + 0];
  94165. var i1 = indices[pos + 1];
  94166. var i2 = indices[pos + 2];
  94167. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94168. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94169. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94170. var triangle = new DecimationTriangle([v0, v1, v2]);
  94171. triangle.originalOffset = pos;
  94172. _this.triangles.push(triangle);
  94173. };
  94174. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94175. _this.init(callback);
  94176. });
  94177. });
  94178. };
  94179. QuadraticErrorSimplification.prototype.init = function (callback) {
  94180. var _this = this;
  94181. var triangleInit1 = function (i) {
  94182. var t = _this.triangles[i];
  94183. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94184. for (var j = 0; j < 3; j++) {
  94185. 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))));
  94186. }
  94187. };
  94188. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94189. var triangleInit2 = function (i) {
  94190. var t = _this.triangles[i];
  94191. for (var j = 0; j < 3; ++j) {
  94192. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94193. }
  94194. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94195. };
  94196. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94197. callback();
  94198. });
  94199. });
  94200. };
  94201. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94202. var newTriangles = [];
  94203. var i;
  94204. for (i = 0; i < this.vertices.length; ++i) {
  94205. this.vertices[i].triangleCount = 0;
  94206. }
  94207. var t;
  94208. var j;
  94209. for (i = 0; i < this.triangles.length; ++i) {
  94210. if (!this.triangles[i].deleted) {
  94211. t = this.triangles[i];
  94212. for (j = 0; j < 3; ++j) {
  94213. t.vertices[j].triangleCount = 1;
  94214. }
  94215. newTriangles.push(t);
  94216. }
  94217. }
  94218. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94219. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94220. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94221. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94222. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94223. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94224. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94225. var vertexCount = 0;
  94226. for (i = 0; i < this.vertices.length; ++i) {
  94227. var vertex = this.vertices[i];
  94228. vertex.id = vertexCount;
  94229. if (vertex.triangleCount) {
  94230. vertex.originalOffsets.forEach(function (originalOffset) {
  94231. if (!normalData) {
  94232. return;
  94233. }
  94234. newPositionData.push(vertex.position.x);
  94235. newPositionData.push(vertex.position.y);
  94236. newPositionData.push(vertex.position.z);
  94237. newNormalData.push(normalData[originalOffset * 3]);
  94238. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94239. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94240. if (uvs && uvs.length) {
  94241. newUVsData.push(uvs[(originalOffset * 2)]);
  94242. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94243. }
  94244. else if (colorsData && colorsData.length) {
  94245. newColorsData.push(colorsData[(originalOffset * 4)]);
  94246. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94247. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94248. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94249. }
  94250. ++vertexCount;
  94251. });
  94252. }
  94253. }
  94254. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94255. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94256. var submeshesArray = this._reconstructedMesh.subMeshes;
  94257. this._reconstructedMesh.subMeshes = [];
  94258. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94259. var originalIndices = this._mesh.getIndices();
  94260. for (i = 0; i < newTriangles.length; ++i) {
  94261. t = newTriangles[i]; //now get the new referencing point for each vertex
  94262. [0, 1, 2].forEach(function (idx) {
  94263. var id = originalIndices[t.originalOffset + idx];
  94264. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94265. if (offset < 0)
  94266. offset = 0;
  94267. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94268. });
  94269. }
  94270. //overwriting the old vertex buffers and indices.
  94271. this._reconstructedMesh.setIndices(newIndicesArray);
  94272. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94273. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94274. if (newUVsData.length > 0)
  94275. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94276. if (newColorsData.length > 0)
  94277. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94278. //create submesh
  94279. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94280. if (submeshIndex > 0) {
  94281. this._reconstructedMesh.subMeshes = [];
  94282. submeshesArray.forEach(function (submesh) {
  94283. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94284. });
  94285. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94286. }
  94287. };
  94288. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94289. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94290. this._reconstructedMesh.material = this._mesh.material;
  94291. this._reconstructedMesh.parent = this._mesh.parent;
  94292. this._reconstructedMesh.isVisible = false;
  94293. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94294. };
  94295. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94296. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94297. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94298. if (t.deleted)
  94299. continue;
  94300. var s = this.references[vertex1.triangleStart + i].vertexId;
  94301. var v1 = t.vertices[(s + 1) % 3];
  94302. var v2 = t.vertices[(s + 2) % 3];
  94303. if ((v1 === vertex2 || v2 === vertex2)) {
  94304. deletedArray[i] = true;
  94305. delTr.push(t);
  94306. continue;
  94307. }
  94308. var d1 = v1.position.subtract(point);
  94309. d1 = d1.normalize();
  94310. var d2 = v2.position.subtract(point);
  94311. d2 = d2.normalize();
  94312. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94313. return true;
  94314. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94315. deletedArray[i] = false;
  94316. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94317. return true;
  94318. }
  94319. return false;
  94320. };
  94321. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94322. var newDeleted = deletedTriangles;
  94323. for (var i = 0; i < vertex.triangleCount; ++i) {
  94324. var ref = this.references[vertex.triangleStart + i];
  94325. var t = this.triangles[ref.triangleId];
  94326. if (t.deleted)
  94327. continue;
  94328. if (deletedArray[i] && t.deletePending) {
  94329. t.deleted = true;
  94330. newDeleted++;
  94331. continue;
  94332. }
  94333. t.vertices[ref.vertexId] = origVertex;
  94334. t.isDirty = true;
  94335. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94336. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94337. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94338. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94339. this.references.push(ref);
  94340. }
  94341. return newDeleted;
  94342. };
  94343. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94344. for (var i = 0; i < this.vertices.length; ++i) {
  94345. var vCount = [];
  94346. var vId = [];
  94347. var v = this.vertices[i];
  94348. var j;
  94349. for (j = 0; j < v.triangleCount; ++j) {
  94350. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94351. for (var ii = 0; ii < 3; ii++) {
  94352. var ofs = 0;
  94353. var vv = triangle.vertices[ii];
  94354. while (ofs < vCount.length) {
  94355. if (vId[ofs] === vv.id)
  94356. break;
  94357. ++ofs;
  94358. }
  94359. if (ofs === vCount.length) {
  94360. vCount.push(1);
  94361. vId.push(vv.id);
  94362. }
  94363. else {
  94364. vCount[ofs]++;
  94365. }
  94366. }
  94367. }
  94368. for (j = 0; j < vCount.length; ++j) {
  94369. if (vCount[j] === 1) {
  94370. this.vertices[vId[j]].isBorder = true;
  94371. }
  94372. else {
  94373. this.vertices[vId[j]].isBorder = false;
  94374. }
  94375. }
  94376. }
  94377. };
  94378. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94379. if (identifyBorders === void 0) { identifyBorders = false; }
  94380. var i;
  94381. if (!identifyBorders) {
  94382. var newTrianglesVector = [];
  94383. for (i = 0; i < this.triangles.length; ++i) {
  94384. if (!this.triangles[i].deleted) {
  94385. newTrianglesVector.push(this.triangles[i]);
  94386. }
  94387. }
  94388. this.triangles = newTrianglesVector;
  94389. }
  94390. for (i = 0; i < this.vertices.length; ++i) {
  94391. this.vertices[i].triangleCount = 0;
  94392. this.vertices[i].triangleStart = 0;
  94393. }
  94394. var t;
  94395. var j;
  94396. var v;
  94397. for (i = 0; i < this.triangles.length; ++i) {
  94398. t = this.triangles[i];
  94399. for (j = 0; j < 3; ++j) {
  94400. v = t.vertices[j];
  94401. v.triangleCount++;
  94402. }
  94403. }
  94404. var tStart = 0;
  94405. for (i = 0; i < this.vertices.length; ++i) {
  94406. this.vertices[i].triangleStart = tStart;
  94407. tStart += this.vertices[i].triangleCount;
  94408. this.vertices[i].triangleCount = 0;
  94409. }
  94410. var newReferences = new Array(this.triangles.length * 3);
  94411. for (i = 0; i < this.triangles.length; ++i) {
  94412. t = this.triangles[i];
  94413. for (j = 0; j < 3; ++j) {
  94414. v = t.vertices[j];
  94415. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94416. v.triangleCount++;
  94417. }
  94418. }
  94419. this.references = newReferences;
  94420. if (identifyBorders) {
  94421. this.identifyBorder();
  94422. }
  94423. };
  94424. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94425. var x = point.x;
  94426. var y = point.y;
  94427. var z = point.z;
  94428. 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
  94429. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94430. };
  94431. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94432. var q = vertex1.q.add(vertex2.q);
  94433. var border = vertex1.isBorder && vertex2.isBorder;
  94434. var error = 0;
  94435. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94436. if (qDet !== 0 && !border) {
  94437. if (!pointResult) {
  94438. pointResult = BABYLON.Vector3.Zero();
  94439. }
  94440. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94441. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94442. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94443. error = this.vertexError(q, pointResult);
  94444. }
  94445. else {
  94446. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94447. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94448. var error1 = this.vertexError(q, vertex1.position);
  94449. var error2 = this.vertexError(q, vertex2.position);
  94450. var error3 = this.vertexError(q, p3);
  94451. error = Math.min(error1, error2, error3);
  94452. if (error === error1) {
  94453. if (pointResult) {
  94454. pointResult.copyFrom(vertex1.position);
  94455. }
  94456. }
  94457. else if (error === error2) {
  94458. if (pointResult) {
  94459. pointResult.copyFrom(vertex2.position);
  94460. }
  94461. }
  94462. else {
  94463. if (pointResult) {
  94464. pointResult.copyFrom(p3);
  94465. }
  94466. }
  94467. }
  94468. return error;
  94469. };
  94470. return QuadraticErrorSimplification;
  94471. }());
  94472. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  94473. })(BABYLON || (BABYLON = {}));
  94474. //# sourceMappingURL=babylon.meshSimplification.js.map
  94475. var BABYLON;
  94476. (function (BABYLON) {
  94477. var MeshLODLevel = /** @class */ (function () {
  94478. function MeshLODLevel(distance, mesh) {
  94479. this.distance = distance;
  94480. this.mesh = mesh;
  94481. }
  94482. return MeshLODLevel;
  94483. }());
  94484. BABYLON.MeshLODLevel = MeshLODLevel;
  94485. })(BABYLON || (BABYLON = {}));
  94486. //# sourceMappingURL=babylon.meshLODLevel.js.map
  94487. var BABYLON;
  94488. (function (BABYLON) {
  94489. /**
  94490. * Defines the root class used to create scene optimization to use with SceneOptimizer
  94491. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94492. */
  94493. var SceneOptimization = /** @class */ (function () {
  94494. /**
  94495. * Creates the SceneOptimization object
  94496. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94497. * @param desc defines the description associated with the optimization
  94498. */
  94499. function SceneOptimization(
  94500. /**
  94501. * Defines the priority of this optimization (0 by default which means first in the list)
  94502. */
  94503. priority) {
  94504. if (priority === void 0) { priority = 0; }
  94505. this.priority = priority;
  94506. }
  94507. /**
  94508. * Gets a string describing the action executed by the current optimization
  94509. * @returns description string
  94510. */
  94511. SceneOptimization.prototype.getDescription = function () {
  94512. return "";
  94513. };
  94514. /**
  94515. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94516. * @param scene defines the current scene where to apply this optimization
  94517. * @param optimizer defines the current optimizer
  94518. * @returns true if everything that can be done was applied
  94519. */
  94520. SceneOptimization.prototype.apply = function (scene, optimizer) {
  94521. return true;
  94522. };
  94523. ;
  94524. return SceneOptimization;
  94525. }());
  94526. BABYLON.SceneOptimization = SceneOptimization;
  94527. /**
  94528. * Defines an optimization used to reduce the size of render target textures
  94529. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94530. */
  94531. var TextureOptimization = /** @class */ (function (_super) {
  94532. __extends(TextureOptimization, _super);
  94533. /**
  94534. * Creates the TextureOptimization object
  94535. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94536. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  94537. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94538. */
  94539. function TextureOptimization(
  94540. /**
  94541. * Defines the priority of this optimization (0 by default which means first in the list)
  94542. */
  94543. priority,
  94544. /**
  94545. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  94546. */
  94547. maximumSize,
  94548. /**
  94549. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94550. */
  94551. step) {
  94552. if (priority === void 0) { priority = 0; }
  94553. if (maximumSize === void 0) { maximumSize = 1024; }
  94554. if (step === void 0) { step = 0.5; }
  94555. var _this = _super.call(this, priority) || this;
  94556. _this.priority = priority;
  94557. _this.maximumSize = maximumSize;
  94558. _this.step = step;
  94559. return _this;
  94560. }
  94561. /**
  94562. * Gets a string describing the action executed by the current optimization
  94563. * @returns description string
  94564. */
  94565. TextureOptimization.prototype.getDescription = function () {
  94566. return "Reducing render target texture size to " + this.maximumSize;
  94567. };
  94568. /**
  94569. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94570. * @param scene defines the current scene where to apply this optimization
  94571. * @param optimizer defines the current optimizer
  94572. * @returns true if everything that can be done was applied
  94573. */
  94574. TextureOptimization.prototype.apply = function (scene, optimizer) {
  94575. var allDone = true;
  94576. for (var index = 0; index < scene.textures.length; index++) {
  94577. var texture = scene.textures[index];
  94578. if (!texture.canRescale || texture.getContext) {
  94579. continue;
  94580. }
  94581. var currentSize = texture.getSize();
  94582. var maxDimension = Math.max(currentSize.width, currentSize.height);
  94583. if (maxDimension > this.maximumSize) {
  94584. texture.scale(this.step);
  94585. allDone = false;
  94586. }
  94587. }
  94588. return allDone;
  94589. };
  94590. return TextureOptimization;
  94591. }(SceneOptimization));
  94592. BABYLON.TextureOptimization = TextureOptimization;
  94593. /**
  94594. * Defines an optimization used to increase or decrease the rendering resolution
  94595. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94596. */
  94597. var HardwareScalingOptimization = /** @class */ (function (_super) {
  94598. __extends(HardwareScalingOptimization, _super);
  94599. /**
  94600. * Creates the HardwareScalingOptimization object
  94601. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94602. * @param maximumScale defines the maximum scale to use (2 by default)
  94603. * @param step defines the step to use between two passes (0.5 by default)
  94604. */
  94605. function HardwareScalingOptimization(
  94606. /**
  94607. * Defines the priority of this optimization (0 by default which means first in the list)
  94608. */
  94609. priority,
  94610. /**
  94611. * Defines the maximum scale to use (2 by default)
  94612. */
  94613. maximumScale,
  94614. /**
  94615. * Defines the step to use between two passes (0.5 by default)
  94616. */
  94617. step) {
  94618. if (priority === void 0) { priority = 0; }
  94619. if (maximumScale === void 0) { maximumScale = 2; }
  94620. if (step === void 0) { step = 0.25; }
  94621. var _this = _super.call(this, priority) || this;
  94622. _this.priority = priority;
  94623. _this.maximumScale = maximumScale;
  94624. _this.step = step;
  94625. _this._currentScale = -1;
  94626. _this._directionOffset = 1;
  94627. return _this;
  94628. }
  94629. /**
  94630. * Gets a string describing the action executed by the current optimization
  94631. * @return description string
  94632. */
  94633. HardwareScalingOptimization.prototype.getDescription = function () {
  94634. return "Setting hardware scaling level to " + this._currentScale;
  94635. };
  94636. /**
  94637. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94638. * @param scene defines the current scene where to apply this optimization
  94639. * @param optimizer defines the current optimizer
  94640. * @returns true if everything that can be done was applied
  94641. */
  94642. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  94643. if (this._currentScale === -1) {
  94644. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  94645. if (this._currentScale > this.maximumScale) {
  94646. this._directionOffset = -1;
  94647. }
  94648. }
  94649. this._currentScale += this._directionOffset * this.step;
  94650. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  94651. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  94652. };
  94653. ;
  94654. return HardwareScalingOptimization;
  94655. }(SceneOptimization));
  94656. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  94657. /**
  94658. * Defines an optimization used to remove shadows
  94659. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94660. */
  94661. var ShadowsOptimization = /** @class */ (function (_super) {
  94662. __extends(ShadowsOptimization, _super);
  94663. function ShadowsOptimization() {
  94664. return _super !== null && _super.apply(this, arguments) || this;
  94665. }
  94666. /**
  94667. * Gets a string describing the action executed by the current optimization
  94668. * @return description string
  94669. */
  94670. ShadowsOptimization.prototype.getDescription = function () {
  94671. return "Turning shadows on/off";
  94672. };
  94673. /**
  94674. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94675. * @param scene defines the current scene where to apply this optimization
  94676. * @param optimizer defines the current optimizer
  94677. * @returns true if everything that can be done was applied
  94678. */
  94679. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  94680. scene.shadowsEnabled = optimizer.isInImprovementMode;
  94681. return true;
  94682. };
  94683. ;
  94684. return ShadowsOptimization;
  94685. }(SceneOptimization));
  94686. BABYLON.ShadowsOptimization = ShadowsOptimization;
  94687. /**
  94688. * Defines an optimization used to turn post-processes off
  94689. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94690. */
  94691. var PostProcessesOptimization = /** @class */ (function (_super) {
  94692. __extends(PostProcessesOptimization, _super);
  94693. function PostProcessesOptimization() {
  94694. return _super !== null && _super.apply(this, arguments) || this;
  94695. }
  94696. /**
  94697. * Gets a string describing the action executed by the current optimization
  94698. * @return description string
  94699. */
  94700. PostProcessesOptimization.prototype.getDescription = function () {
  94701. return "Turning post-processes on/off";
  94702. };
  94703. /**
  94704. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94705. * @param scene defines the current scene where to apply this optimization
  94706. * @param optimizer defines the current optimizer
  94707. * @returns true if everything that can be done was applied
  94708. */
  94709. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  94710. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  94711. return true;
  94712. };
  94713. ;
  94714. return PostProcessesOptimization;
  94715. }(SceneOptimization));
  94716. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  94717. /**
  94718. * Defines an optimization used to turn lens flares off
  94719. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94720. */
  94721. var LensFlaresOptimization = /** @class */ (function (_super) {
  94722. __extends(LensFlaresOptimization, _super);
  94723. function LensFlaresOptimization() {
  94724. return _super !== null && _super.apply(this, arguments) || this;
  94725. }
  94726. /**
  94727. * Gets a string describing the action executed by the current optimization
  94728. * @return description string
  94729. */
  94730. LensFlaresOptimization.prototype.getDescription = function () {
  94731. return "Turning lens flares on/off";
  94732. };
  94733. /**
  94734. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94735. * @param scene defines the current scene where to apply this optimization
  94736. * @param optimizer defines the current optimizer
  94737. * @returns true if everything that can be done was applied
  94738. */
  94739. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  94740. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  94741. return true;
  94742. };
  94743. ;
  94744. return LensFlaresOptimization;
  94745. }(SceneOptimization));
  94746. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  94747. /**
  94748. * Defines an optimization based on user defined callback.
  94749. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94750. */
  94751. var CustomOptimization = /** @class */ (function (_super) {
  94752. __extends(CustomOptimization, _super);
  94753. function CustomOptimization() {
  94754. return _super !== null && _super.apply(this, arguments) || this;
  94755. }
  94756. /**
  94757. * Gets a string describing the action executed by the current optimization
  94758. * @returns description string
  94759. */
  94760. CustomOptimization.prototype.getDescription = function () {
  94761. if (this.onGetDescription) {
  94762. return this.onGetDescription();
  94763. }
  94764. return "Running user defined callback";
  94765. };
  94766. /**
  94767. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94768. * @param scene defines the current scene where to apply this optimization
  94769. * @param optimizer defines the current optimizer
  94770. * @returns true if everything that can be done was applied
  94771. */
  94772. CustomOptimization.prototype.apply = function (scene, optimizer) {
  94773. if (this.onApply) {
  94774. return this.onApply(scene, optimizer);
  94775. }
  94776. return true;
  94777. };
  94778. ;
  94779. return CustomOptimization;
  94780. }(SceneOptimization));
  94781. BABYLON.CustomOptimization = CustomOptimization;
  94782. /**
  94783. * Defines an optimization used to turn particles off
  94784. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94785. */
  94786. var ParticlesOptimization = /** @class */ (function (_super) {
  94787. __extends(ParticlesOptimization, _super);
  94788. function ParticlesOptimization() {
  94789. return _super !== null && _super.apply(this, arguments) || this;
  94790. }
  94791. /**
  94792. * Gets a string describing the action executed by the current optimization
  94793. * @return description string
  94794. */
  94795. ParticlesOptimization.prototype.getDescription = function () {
  94796. return "Turning particles on/off";
  94797. };
  94798. /**
  94799. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94800. * @param scene defines the current scene where to apply this optimization
  94801. * @param optimizer defines the current optimizer
  94802. * @returns true if everything that can be done was applied
  94803. */
  94804. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  94805. scene.particlesEnabled = optimizer.isInImprovementMode;
  94806. return true;
  94807. };
  94808. ;
  94809. return ParticlesOptimization;
  94810. }(SceneOptimization));
  94811. BABYLON.ParticlesOptimization = ParticlesOptimization;
  94812. /**
  94813. * Defines an optimization used to turn render targets off
  94814. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94815. */
  94816. var RenderTargetsOptimization = /** @class */ (function (_super) {
  94817. __extends(RenderTargetsOptimization, _super);
  94818. function RenderTargetsOptimization() {
  94819. return _super !== null && _super.apply(this, arguments) || this;
  94820. }
  94821. /**
  94822. * Gets a string describing the action executed by the current optimization
  94823. * @return description string
  94824. */
  94825. RenderTargetsOptimization.prototype.getDescription = function () {
  94826. return "Turning render targets off";
  94827. };
  94828. /**
  94829. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94830. * @param scene defines the current scene where to apply this optimization
  94831. * @param optimizer defines the current optimizer
  94832. * @returns true if everything that can be done was applied
  94833. */
  94834. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  94835. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  94836. return true;
  94837. };
  94838. ;
  94839. return RenderTargetsOptimization;
  94840. }(SceneOptimization));
  94841. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  94842. /**
  94843. * Defines an optimization used to merge meshes with compatible materials
  94844. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94845. */
  94846. var MergeMeshesOptimization = /** @class */ (function (_super) {
  94847. __extends(MergeMeshesOptimization, _super);
  94848. function MergeMeshesOptimization() {
  94849. var _this = _super !== null && _super.apply(this, arguments) || this;
  94850. _this._canBeMerged = function (abstractMesh) {
  94851. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  94852. return false;
  94853. }
  94854. var mesh = abstractMesh;
  94855. if (!mesh.isVisible || !mesh.isEnabled()) {
  94856. return false;
  94857. }
  94858. if (mesh.instances.length > 0) {
  94859. return false;
  94860. }
  94861. if (mesh.skeleton || mesh.hasLODLevels) {
  94862. return false;
  94863. }
  94864. if (mesh.parent) {
  94865. return false;
  94866. }
  94867. return true;
  94868. };
  94869. return _this;
  94870. }
  94871. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  94872. /**
  94873. * Gets or sets a boolean which defines if optimization octree has to be updated
  94874. */
  94875. get: function () {
  94876. return MergeMeshesOptimization._UpdateSelectionTree;
  94877. },
  94878. /**
  94879. * Gets or sets a boolean which defines if optimization octree has to be updated
  94880. */
  94881. set: function (value) {
  94882. MergeMeshesOptimization._UpdateSelectionTree = value;
  94883. },
  94884. enumerable: true,
  94885. configurable: true
  94886. });
  94887. /**
  94888. * Gets a string describing the action executed by the current optimization
  94889. * @return description string
  94890. */
  94891. MergeMeshesOptimization.prototype.getDescription = function () {
  94892. return "Merging similar meshes together";
  94893. };
  94894. /**
  94895. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94896. * @param scene defines the current scene where to apply this optimization
  94897. * @param optimizer defines the current optimizer
  94898. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  94899. * @returns true if everything that can be done was applied
  94900. */
  94901. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  94902. var globalPool = scene.meshes.slice(0);
  94903. var globalLength = globalPool.length;
  94904. for (var index = 0; index < globalLength; index++) {
  94905. var currentPool = new Array();
  94906. var current = globalPool[index];
  94907. // Checks
  94908. if (!this._canBeMerged(current)) {
  94909. continue;
  94910. }
  94911. currentPool.push(current);
  94912. // Find compatible meshes
  94913. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  94914. var otherMesh = globalPool[subIndex];
  94915. if (!this._canBeMerged(otherMesh)) {
  94916. continue;
  94917. }
  94918. if (otherMesh.material !== current.material) {
  94919. continue;
  94920. }
  94921. if (otherMesh.checkCollisions !== current.checkCollisions) {
  94922. continue;
  94923. }
  94924. currentPool.push(otherMesh);
  94925. globalLength--;
  94926. globalPool.splice(subIndex, 1);
  94927. subIndex--;
  94928. }
  94929. if (currentPool.length < 2) {
  94930. continue;
  94931. }
  94932. // Merge meshes
  94933. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  94934. }
  94935. if (updateSelectionTree != undefined) {
  94936. if (updateSelectionTree) {
  94937. scene.createOrUpdateSelectionOctree();
  94938. }
  94939. }
  94940. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  94941. scene.createOrUpdateSelectionOctree();
  94942. }
  94943. return true;
  94944. };
  94945. ;
  94946. MergeMeshesOptimization._UpdateSelectionTree = false;
  94947. return MergeMeshesOptimization;
  94948. }(SceneOptimization));
  94949. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  94950. /**
  94951. * Defines a list of options used by SceneOptimizer
  94952. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94953. */
  94954. var SceneOptimizerOptions = /** @class */ (function () {
  94955. /**
  94956. * Creates a new list of options used by SceneOptimizer
  94957. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  94958. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  94959. */
  94960. function SceneOptimizerOptions(
  94961. /**
  94962. * Defines the target frame rate to reach (60 by default)
  94963. */
  94964. targetFrameRate,
  94965. /**
  94966. * Defines the interval between two checkes (2000ms by default)
  94967. */
  94968. trackerDuration) {
  94969. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  94970. if (trackerDuration === void 0) { trackerDuration = 2000; }
  94971. this.targetFrameRate = targetFrameRate;
  94972. this.trackerDuration = trackerDuration;
  94973. /**
  94974. * Gets the list of optimizations to apply
  94975. */
  94976. this.optimizations = new Array();
  94977. }
  94978. /**
  94979. * Add a new optimization
  94980. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  94981. * @returns the current SceneOptimizerOptions
  94982. */
  94983. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  94984. this.optimizations.push(optimization);
  94985. return this;
  94986. };
  94987. /**
  94988. * Add a new custom optimization
  94989. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  94990. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  94991. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94992. * @returns the current SceneOptimizerOptions
  94993. */
  94994. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  94995. if (priority === void 0) { priority = 0; }
  94996. var optimization = new CustomOptimization(priority);
  94997. optimization.onApply = onApply;
  94998. optimization.onGetDescription = onGetDescription;
  94999. this.optimizations.push(optimization);
  95000. return this;
  95001. };
  95002. /**
  95003. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95004. * @param targetFrameRate defines the target frame rate (60 by default)
  95005. * @returns a SceneOptimizerOptions object
  95006. */
  95007. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95008. var result = new SceneOptimizerOptions(targetFrameRate);
  95009. var priority = 0;
  95010. result.addOptimization(new MergeMeshesOptimization(priority));
  95011. result.addOptimization(new ShadowsOptimization(priority));
  95012. result.addOptimization(new LensFlaresOptimization(priority));
  95013. // Next priority
  95014. priority++;
  95015. result.addOptimization(new PostProcessesOptimization(priority));
  95016. result.addOptimization(new ParticlesOptimization(priority));
  95017. // Next priority
  95018. priority++;
  95019. result.addOptimization(new TextureOptimization(priority, 1024));
  95020. return result;
  95021. };
  95022. /**
  95023. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95024. * @param targetFrameRate defines the target frame rate (60 by default)
  95025. * @returns a SceneOptimizerOptions object
  95026. */
  95027. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95028. var result = new SceneOptimizerOptions(targetFrameRate);
  95029. var priority = 0;
  95030. result.addOptimization(new MergeMeshesOptimization(priority));
  95031. result.addOptimization(new ShadowsOptimization(priority));
  95032. result.addOptimization(new LensFlaresOptimization(priority));
  95033. // Next priority
  95034. priority++;
  95035. result.addOptimization(new PostProcessesOptimization(priority));
  95036. result.addOptimization(new ParticlesOptimization(priority));
  95037. // Next priority
  95038. priority++;
  95039. result.addOptimization(new TextureOptimization(priority, 512));
  95040. // Next priority
  95041. priority++;
  95042. result.addOptimization(new RenderTargetsOptimization(priority));
  95043. // Next priority
  95044. priority++;
  95045. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95046. return result;
  95047. };
  95048. /**
  95049. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95050. * @param targetFrameRate defines the target frame rate (60 by default)
  95051. * @returns a SceneOptimizerOptions object
  95052. */
  95053. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95054. var result = new SceneOptimizerOptions(targetFrameRate);
  95055. var priority = 0;
  95056. result.addOptimization(new MergeMeshesOptimization(priority));
  95057. result.addOptimization(new ShadowsOptimization(priority));
  95058. result.addOptimization(new LensFlaresOptimization(priority));
  95059. // Next priority
  95060. priority++;
  95061. result.addOptimization(new PostProcessesOptimization(priority));
  95062. result.addOptimization(new ParticlesOptimization(priority));
  95063. // Next priority
  95064. priority++;
  95065. result.addOptimization(new TextureOptimization(priority, 256));
  95066. // Next priority
  95067. priority++;
  95068. result.addOptimization(new RenderTargetsOptimization(priority));
  95069. // Next priority
  95070. priority++;
  95071. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95072. return result;
  95073. };
  95074. return SceneOptimizerOptions;
  95075. }());
  95076. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95077. /**
  95078. * Class used to run optimizations in order to reach a target frame rate
  95079. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95080. */
  95081. var SceneOptimizer = /** @class */ (function () {
  95082. /**
  95083. * Creates a new SceneOptimizer
  95084. * @param scene defines the scene to work on
  95085. * @param options defines the options to use with the SceneOptimizer
  95086. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95087. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  95088. */
  95089. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95090. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95091. if (improvementMode === void 0) { improvementMode = false; }
  95092. var _this = this;
  95093. this._isRunning = false;
  95094. this._currentPriorityLevel = 0;
  95095. this._targetFrameRate = 60;
  95096. this._trackerDuration = 2000;
  95097. this._currentFrameRate = 0;
  95098. this._improvementMode = false;
  95099. /**
  95100. * Defines an observable called when the optimizer reaches the target frame rate
  95101. */
  95102. this.onSuccessObservable = new BABYLON.Observable();
  95103. /**
  95104. * Defines an observable called when the optimizer enables an optimization
  95105. */
  95106. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95107. /**
  95108. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95109. */
  95110. this.onFailureObservable = new BABYLON.Observable();
  95111. if (!options) {
  95112. this._options = new SceneOptimizerOptions();
  95113. }
  95114. else {
  95115. this._options = options;
  95116. }
  95117. if (this._options.targetFrameRate) {
  95118. this._targetFrameRate = this._options.targetFrameRate;
  95119. }
  95120. if (this._options.trackerDuration) {
  95121. this._trackerDuration = this._options.trackerDuration;
  95122. }
  95123. if (autoGeneratePriorities) {
  95124. var priority = 0;
  95125. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95126. var optim = _a[_i];
  95127. optim.priority = priority++;
  95128. }
  95129. }
  95130. this._improvementMode = improvementMode;
  95131. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95132. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95133. _this._sceneDisposeObserver = null;
  95134. _this.dispose();
  95135. });
  95136. }
  95137. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95138. /**
  95139. * Gets a boolean indicating if the optimizer is in improvement mode
  95140. */
  95141. get: function () {
  95142. return this._improvementMode;
  95143. },
  95144. enumerable: true,
  95145. configurable: true
  95146. });
  95147. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95148. /**
  95149. * Gets the current priority level (0 at start)
  95150. */
  95151. get: function () {
  95152. return this._currentPriorityLevel;
  95153. },
  95154. enumerable: true,
  95155. configurable: true
  95156. });
  95157. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95158. /**
  95159. * Gets the current frame rate checked by the SceneOptimizer
  95160. */
  95161. get: function () {
  95162. return this._currentFrameRate;
  95163. },
  95164. enumerable: true,
  95165. configurable: true
  95166. });
  95167. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95168. /**
  95169. * Gets or sets the current target frame rate (60 by default)
  95170. */
  95171. get: function () {
  95172. return this._targetFrameRate;
  95173. },
  95174. /**
  95175. * Gets or sets the current target frame rate (60 by default)
  95176. */
  95177. set: function (value) {
  95178. this._targetFrameRate = value;
  95179. },
  95180. enumerable: true,
  95181. configurable: true
  95182. });
  95183. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95184. /**
  95185. * Gets or sets the current interval between two checks (every 2000ms by default)
  95186. */
  95187. get: function () {
  95188. return this._trackerDuration;
  95189. },
  95190. /**
  95191. * Gets or sets the current interval between two checks (every 2000ms by default)
  95192. */
  95193. set: function (value) {
  95194. this._trackerDuration = value;
  95195. },
  95196. enumerable: true,
  95197. configurable: true
  95198. });
  95199. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95200. /**
  95201. * Gets the list of active optimizations
  95202. */
  95203. get: function () {
  95204. return this._options.optimizations;
  95205. },
  95206. enumerable: true,
  95207. configurable: true
  95208. });
  95209. /**
  95210. * Stops the current optimizer
  95211. */
  95212. SceneOptimizer.prototype.stop = function () {
  95213. this._isRunning = false;
  95214. };
  95215. /**
  95216. * Reset the optimizer to initial step (current priority level = 0)
  95217. */
  95218. SceneOptimizer.prototype.reset = function () {
  95219. this._currentPriorityLevel = 0;
  95220. };
  95221. /**
  95222. * Start the optimizer. By default it will try to reach a specific framerate
  95223. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95224. */
  95225. SceneOptimizer.prototype.start = function () {
  95226. var _this = this;
  95227. if (this._isRunning) {
  95228. return;
  95229. }
  95230. this._isRunning = true;
  95231. // Let's wait for the scene to be ready before running our check
  95232. this._scene.executeWhenReady(function () {
  95233. setTimeout(function () {
  95234. _this._checkCurrentState();
  95235. }, _this._trackerDuration);
  95236. });
  95237. };
  95238. SceneOptimizer.prototype._checkCurrentState = function () {
  95239. var _this = this;
  95240. if (!this._isRunning) {
  95241. return;
  95242. }
  95243. var scene = this._scene;
  95244. var options = this._options;
  95245. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95246. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95247. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95248. this._isRunning = false;
  95249. this.onSuccessObservable.notifyObservers(this);
  95250. return;
  95251. }
  95252. // Apply current level of optimizations
  95253. var allDone = true;
  95254. var noOptimizationApplied = true;
  95255. for (var index = 0; index < options.optimizations.length; index++) {
  95256. var optimization = options.optimizations[index];
  95257. if (optimization.priority === this._currentPriorityLevel) {
  95258. noOptimizationApplied = false;
  95259. allDone = allDone && optimization.apply(scene, this);
  95260. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95261. }
  95262. }
  95263. // If no optimization was applied, this is a failure :(
  95264. if (noOptimizationApplied) {
  95265. this._isRunning = false;
  95266. this.onFailureObservable.notifyObservers(this);
  95267. return;
  95268. }
  95269. // If all optimizations were done, move to next level
  95270. if (allDone) {
  95271. this._currentPriorityLevel++;
  95272. }
  95273. // Let's the system running for a specific amount of time before checking FPS
  95274. scene.executeWhenReady(function () {
  95275. setTimeout(function () {
  95276. _this._checkCurrentState();
  95277. }, _this._trackerDuration);
  95278. });
  95279. };
  95280. /**
  95281. * Release all resources
  95282. */
  95283. SceneOptimizer.prototype.dispose = function () {
  95284. this.stop();
  95285. this.onSuccessObservable.clear();
  95286. this.onFailureObservable.clear();
  95287. this.onNewOptimizationAppliedObservable.clear();
  95288. if (this._sceneDisposeObserver) {
  95289. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95290. }
  95291. };
  95292. /**
  95293. * Helper function to create a SceneOptimizer with one single line of code
  95294. * @param scene defines the scene to work on
  95295. * @param options defines the options to use with the SceneOptimizer
  95296. * @param onSuccess defines a callback to call on success
  95297. * @param onFailure defines a callback to call on failure
  95298. * @returns the new SceneOptimizer object
  95299. */
  95300. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95301. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95302. if (onSuccess) {
  95303. optimizer.onSuccessObservable.add(function () {
  95304. onSuccess();
  95305. });
  95306. }
  95307. if (onFailure) {
  95308. optimizer.onFailureObservable.add(function () {
  95309. onFailure();
  95310. });
  95311. }
  95312. optimizer.start();
  95313. return optimizer;
  95314. };
  95315. return SceneOptimizer;
  95316. }());
  95317. BABYLON.SceneOptimizer = SceneOptimizer;
  95318. })(BABYLON || (BABYLON = {}));
  95319. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95320. var BABYLON;
  95321. (function (BABYLON) {
  95322. var OutlineRenderer = /** @class */ (function () {
  95323. function OutlineRenderer(scene) {
  95324. this.zOffset = 1;
  95325. this._scene = scene;
  95326. }
  95327. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95328. var _this = this;
  95329. if (useOverlay === void 0) { useOverlay = false; }
  95330. var scene = this._scene;
  95331. var engine = this._scene.getEngine();
  95332. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95333. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95334. return;
  95335. }
  95336. var mesh = subMesh.getRenderingMesh();
  95337. var material = subMesh.getMaterial();
  95338. if (!material || !scene.activeCamera) {
  95339. return;
  95340. }
  95341. engine.enableEffect(this._effect);
  95342. // Logarithmic depth
  95343. if (material.useLogarithmicDepth) {
  95344. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95345. }
  95346. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95347. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95348. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95349. // Bones
  95350. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95351. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95352. }
  95353. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95354. // Alpha test
  95355. if (material && material.needAlphaTesting()) {
  95356. var alphaTexture = material.getAlphaTestTexture();
  95357. if (alphaTexture) {
  95358. this._effect.setTexture("diffuseSampler", alphaTexture);
  95359. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95360. }
  95361. }
  95362. engine.setZOffset(-this.zOffset);
  95363. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95364. engine.setZOffset(0);
  95365. };
  95366. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95367. var defines = [];
  95368. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95369. var mesh = subMesh.getMesh();
  95370. var material = subMesh.getMaterial();
  95371. if (material) {
  95372. // Alpha test
  95373. if (material.needAlphaTesting()) {
  95374. defines.push("#define ALPHATEST");
  95375. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95376. attribs.push(BABYLON.VertexBuffer.UVKind);
  95377. defines.push("#define UV1");
  95378. }
  95379. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95380. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95381. defines.push("#define UV2");
  95382. }
  95383. }
  95384. //Logarithmic depth
  95385. if (material.useLogarithmicDepth) {
  95386. defines.push("#define LOGARITHMICDEPTH");
  95387. }
  95388. }
  95389. // Bones
  95390. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95391. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95392. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95393. if (mesh.numBoneInfluencers > 4) {
  95394. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95395. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95396. }
  95397. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95398. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95399. }
  95400. else {
  95401. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95402. }
  95403. // Instances
  95404. if (useInstances) {
  95405. defines.push("#define INSTANCES");
  95406. attribs.push("world0");
  95407. attribs.push("world1");
  95408. attribs.push("world2");
  95409. attribs.push("world3");
  95410. }
  95411. // Get correct effect
  95412. var join = defines.join("\n");
  95413. if (this._cachedDefines !== join) {
  95414. this._cachedDefines = join;
  95415. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95416. }
  95417. return this._effect.isReady();
  95418. };
  95419. return OutlineRenderer;
  95420. }());
  95421. BABYLON.OutlineRenderer = OutlineRenderer;
  95422. })(BABYLON || (BABYLON = {}));
  95423. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95424. var BABYLON;
  95425. (function (BABYLON) {
  95426. var FaceAdjacencies = /** @class */ (function () {
  95427. function FaceAdjacencies() {
  95428. this.edges = new Array();
  95429. this.edgesConnectedCount = 0;
  95430. }
  95431. return FaceAdjacencies;
  95432. }());
  95433. var EdgesRenderer = /** @class */ (function () {
  95434. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95435. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95436. if (epsilon === void 0) { epsilon = 0.95; }
  95437. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95438. this.edgesWidthScalerForOrthographic = 1000.0;
  95439. this.edgesWidthScalerForPerspective = 50.0;
  95440. this._linesPositions = new Array();
  95441. this._linesNormals = new Array();
  95442. this._linesIndices = new Array();
  95443. this._buffers = {};
  95444. this._checkVerticesInsteadOfIndices = false;
  95445. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95446. this.isEnabled = true;
  95447. this._source = source;
  95448. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95449. this._epsilon = epsilon;
  95450. this._prepareRessources();
  95451. this._generateEdgesLines();
  95452. }
  95453. EdgesRenderer.prototype._prepareRessources = function () {
  95454. if (this._lineShader) {
  95455. return;
  95456. }
  95457. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95458. attributes: ["position", "normal"],
  95459. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  95460. });
  95461. this._lineShader.disableDepthWrite = true;
  95462. this._lineShader.backFaceCulling = false;
  95463. };
  95464. EdgesRenderer.prototype._rebuild = function () {
  95465. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95466. if (buffer) {
  95467. buffer._rebuild();
  95468. }
  95469. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95470. if (buffer) {
  95471. buffer._rebuild();
  95472. }
  95473. var scene = this._source.getScene();
  95474. var engine = scene.getEngine();
  95475. this._ib = engine.createIndexBuffer(this._linesIndices);
  95476. };
  95477. EdgesRenderer.prototype.dispose = function () {
  95478. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95479. if (buffer) {
  95480. buffer.dispose();
  95481. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  95482. }
  95483. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95484. if (buffer) {
  95485. buffer.dispose();
  95486. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  95487. }
  95488. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  95489. this._lineShader.dispose();
  95490. };
  95491. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  95492. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  95493. return 0;
  95494. }
  95495. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  95496. return 1;
  95497. }
  95498. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  95499. return 2;
  95500. }
  95501. return -1;
  95502. };
  95503. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  95504. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  95505. return 0;
  95506. }
  95507. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  95508. return 1;
  95509. }
  95510. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  95511. return 2;
  95512. }
  95513. return -1;
  95514. };
  95515. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  95516. var needToCreateLine;
  95517. if (edge === undefined) {
  95518. needToCreateLine = true;
  95519. }
  95520. else {
  95521. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  95522. needToCreateLine = dotProduct < this._epsilon;
  95523. }
  95524. if (needToCreateLine) {
  95525. var offset = this._linesPositions.length / 3;
  95526. var normal = p0.subtract(p1);
  95527. normal.normalize();
  95528. // Positions
  95529. this._linesPositions.push(p0.x);
  95530. this._linesPositions.push(p0.y);
  95531. this._linesPositions.push(p0.z);
  95532. this._linesPositions.push(p0.x);
  95533. this._linesPositions.push(p0.y);
  95534. this._linesPositions.push(p0.z);
  95535. this._linesPositions.push(p1.x);
  95536. this._linesPositions.push(p1.y);
  95537. this._linesPositions.push(p1.z);
  95538. this._linesPositions.push(p1.x);
  95539. this._linesPositions.push(p1.y);
  95540. this._linesPositions.push(p1.z);
  95541. // Normals
  95542. this._linesNormals.push(p1.x);
  95543. this._linesNormals.push(p1.y);
  95544. this._linesNormals.push(p1.z);
  95545. this._linesNormals.push(-1);
  95546. this._linesNormals.push(p1.x);
  95547. this._linesNormals.push(p1.y);
  95548. this._linesNormals.push(p1.z);
  95549. this._linesNormals.push(1);
  95550. this._linesNormals.push(p0.x);
  95551. this._linesNormals.push(p0.y);
  95552. this._linesNormals.push(p0.z);
  95553. this._linesNormals.push(-1);
  95554. this._linesNormals.push(p0.x);
  95555. this._linesNormals.push(p0.y);
  95556. this._linesNormals.push(p0.z);
  95557. this._linesNormals.push(1);
  95558. // Indices
  95559. this._linesIndices.push(offset);
  95560. this._linesIndices.push(offset + 1);
  95561. this._linesIndices.push(offset + 2);
  95562. this._linesIndices.push(offset);
  95563. this._linesIndices.push(offset + 2);
  95564. this._linesIndices.push(offset + 3);
  95565. }
  95566. };
  95567. EdgesRenderer.prototype._generateEdgesLines = function () {
  95568. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95569. var indices = this._source.getIndices();
  95570. if (!indices || !positions) {
  95571. return;
  95572. }
  95573. // First let's find adjacencies
  95574. var adjacencies = new Array();
  95575. var faceNormals = new Array();
  95576. var index;
  95577. var faceAdjacencies;
  95578. // Prepare faces
  95579. for (index = 0; index < indices.length; index += 3) {
  95580. faceAdjacencies = new FaceAdjacencies();
  95581. var p0Index = indices[index];
  95582. var p1Index = indices[index + 1];
  95583. var p2Index = indices[index + 2];
  95584. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  95585. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  95586. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  95587. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  95588. faceNormal.normalize();
  95589. faceNormals.push(faceNormal);
  95590. adjacencies.push(faceAdjacencies);
  95591. }
  95592. // Scan
  95593. for (index = 0; index < adjacencies.length; index++) {
  95594. faceAdjacencies = adjacencies[index];
  95595. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  95596. var otherFaceAdjacencies = adjacencies[otherIndex];
  95597. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  95598. break;
  95599. }
  95600. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  95601. continue;
  95602. }
  95603. var otherP0 = indices[otherIndex * 3];
  95604. var otherP1 = indices[otherIndex * 3 + 1];
  95605. var otherP2 = indices[otherIndex * 3 + 2];
  95606. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  95607. var otherEdgeIndex = 0;
  95608. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  95609. continue;
  95610. }
  95611. switch (edgeIndex) {
  95612. case 0:
  95613. if (this._checkVerticesInsteadOfIndices) {
  95614. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95615. }
  95616. else {
  95617. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  95618. }
  95619. break;
  95620. case 1:
  95621. if (this._checkVerticesInsteadOfIndices) {
  95622. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95623. }
  95624. else {
  95625. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  95626. }
  95627. break;
  95628. case 2:
  95629. if (this._checkVerticesInsteadOfIndices) {
  95630. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95631. }
  95632. else {
  95633. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  95634. }
  95635. break;
  95636. }
  95637. if (otherEdgeIndex === -1) {
  95638. continue;
  95639. }
  95640. faceAdjacencies.edges[edgeIndex] = otherIndex;
  95641. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  95642. faceAdjacencies.edgesConnectedCount++;
  95643. otherFaceAdjacencies.edgesConnectedCount++;
  95644. if (faceAdjacencies.edgesConnectedCount === 3) {
  95645. break;
  95646. }
  95647. }
  95648. }
  95649. }
  95650. // Create lines
  95651. for (index = 0; index < adjacencies.length; index++) {
  95652. // 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
  95653. var current = adjacencies[index];
  95654. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  95655. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  95656. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  95657. }
  95658. // Merge into a single mesh
  95659. var engine = this._source.getScene().getEngine();
  95660. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  95661. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  95662. this._ib = engine.createIndexBuffer(this._linesIndices);
  95663. this._indicesCount = this._linesIndices.length;
  95664. };
  95665. EdgesRenderer.prototype.render = function () {
  95666. var scene = this._source.getScene();
  95667. if (!this._lineShader.isReady() || !scene.activeCamera) {
  95668. return;
  95669. }
  95670. var engine = scene.getEngine();
  95671. this._lineShader._preBind();
  95672. // VBOs
  95673. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  95674. scene.resetCachedMaterial();
  95675. this._lineShader.setColor4("color", this._source.edgesColor);
  95676. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  95677. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  95678. }
  95679. else {
  95680. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  95681. }
  95682. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  95683. this._lineShader.bind(this._source.getWorldMatrix());
  95684. // Draw order
  95685. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  95686. this._lineShader.unbind();
  95687. engine.setDepthWrite(true);
  95688. };
  95689. return EdgesRenderer;
  95690. }());
  95691. BABYLON.EdgesRenderer = EdgesRenderer;
  95692. })(BABYLON || (BABYLON = {}));
  95693. //# sourceMappingURL=babylon.edgesRenderer.js.map
  95694. var BABYLON;
  95695. (function (BABYLON) {
  95696. // Adds the parser to the scene parsers.
  95697. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  95698. if (parsedData.effectLayers) {
  95699. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  95700. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  95701. container.effectLayers.push(effectLayer);
  95702. }
  95703. }
  95704. });
  95705. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  95706. var index = this.effectLayers.indexOf(toRemove);
  95707. if (index !== -1) {
  95708. this.effectLayers.splice(index, 1);
  95709. }
  95710. return index;
  95711. };
  95712. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  95713. this.effectLayers.push(newEffectLayer);
  95714. };
  95715. /**
  95716. * Defines the layer scene component responsible to manage any effect layers
  95717. * in a given scene.
  95718. */
  95719. var EffectLayerSceneComponent = /** @class */ (function () {
  95720. /**
  95721. * Creates a new instance of the component for the given scene
  95722. * @param scene Defines the scene to register the component in
  95723. */
  95724. function EffectLayerSceneComponent(scene) {
  95725. /**
  95726. * The component name helpfull to identify the component in the list of scene components.
  95727. */
  95728. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  95729. this._renderEffects = false;
  95730. this._needStencil = false;
  95731. this._previousStencilState = false;
  95732. this.scene = scene;
  95733. this._engine = scene.getEngine();
  95734. this._effectLayers = scene.effectLayers = new Array();
  95735. }
  95736. /**
  95737. * Registers the component in a given scene
  95738. */
  95739. EffectLayerSceneComponent.prototype.register = function () {
  95740. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  95741. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  95742. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  95743. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  95744. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._draw);
  95745. };
  95746. /**
  95747. * Rebuilds the elements related to this component in case of
  95748. * context lost for instance.
  95749. */
  95750. EffectLayerSceneComponent.prototype.rebuild = function () {
  95751. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  95752. var effectLayer = _a[_i];
  95753. effectLayer._rebuild();
  95754. }
  95755. };
  95756. /**
  95757. * Serializes the component data to the specified json object
  95758. * @param serializationObject The object to serialize to
  95759. */
  95760. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  95761. // Effect layers
  95762. serializationObject.effectLayers = [];
  95763. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  95764. var effectLayer = _a[_i];
  95765. if (effectLayer.serialize) {
  95766. serializationObject.effectLayers.push(effectLayer.serialize());
  95767. }
  95768. }
  95769. };
  95770. /**
  95771. * Adds all the element from the container to the scene
  95772. * @param container the container holding the elements
  95773. */
  95774. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  95775. var _this = this;
  95776. if (!container.effectLayers) {
  95777. return;
  95778. }
  95779. container.effectLayers.forEach(function (o) {
  95780. _this.scene.addEffectLayer(o);
  95781. });
  95782. };
  95783. /**
  95784. * Removes all the elements in the container from the scene
  95785. * @param container contains the elements to remove
  95786. */
  95787. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  95788. var _this = this;
  95789. if (!container.effectLayers) {
  95790. return;
  95791. }
  95792. container.effectLayers.forEach(function (o) {
  95793. _this.scene.removeEffectLayer(o);
  95794. });
  95795. };
  95796. /**
  95797. * Disposes the component and the associated ressources.
  95798. */
  95799. EffectLayerSceneComponent.prototype.dispose = function () {
  95800. while (this._effectLayers.length) {
  95801. this._effectLayers[0].dispose();
  95802. }
  95803. };
  95804. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  95805. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  95806. var layer = _a[_i];
  95807. if (!layer.hasMesh(mesh)) {
  95808. continue;
  95809. }
  95810. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  95811. var subMesh = _c[_b];
  95812. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  95813. return false;
  95814. }
  95815. }
  95816. }
  95817. return true;
  95818. };
  95819. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  95820. this._renderEffects = false;
  95821. this._needStencil = false;
  95822. if (this._effectLayers && this._effectLayers.length > 0) {
  95823. this._previousStencilState = this._engine.getStencilBuffer();
  95824. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  95825. var effectLayer = _a[_i];
  95826. if (effectLayer.shouldRender() &&
  95827. (!effectLayer.camera ||
  95828. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  95829. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  95830. this._renderEffects = true;
  95831. this._needStencil = this._needStencil || effectLayer.needStencil();
  95832. var renderTarget = effectLayer._mainTexture;
  95833. if (renderTarget._shouldRender()) {
  95834. this.scene.incrementRenderId();
  95835. renderTarget.render(false, false);
  95836. }
  95837. }
  95838. }
  95839. this.scene.incrementRenderId();
  95840. }
  95841. };
  95842. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  95843. // Activate effect Layer stencil
  95844. if (this._needStencil) {
  95845. this._engine.setStencilBuffer(true);
  95846. }
  95847. };
  95848. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  95849. // Restore effect Layer stencil
  95850. if (this._needStencil) {
  95851. this._engine.setStencilBuffer(this._previousStencilState);
  95852. }
  95853. };
  95854. EffectLayerSceneComponent.prototype._draw = function (camera) {
  95855. if (this._renderEffects) {
  95856. this._engine.setDepthBuffer(false);
  95857. for (var i = 0; i < this._effectLayers.length; i++) {
  95858. if (this._effectLayers[i].shouldRender()) {
  95859. this._effectLayers[i].render();
  95860. }
  95861. }
  95862. this._engine.setDepthBuffer(true);
  95863. }
  95864. };
  95865. return EffectLayerSceneComponent;
  95866. }());
  95867. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  95868. })(BABYLON || (BABYLON = {}));
  95869. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  95870. var __assign = (this && this.__assign) || Object.assign || function(t) {
  95871. for (var s, i = 1, n = arguments.length; i < n; i++) {
  95872. s = arguments[i];
  95873. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  95874. t[p] = s[p];
  95875. }
  95876. return t;
  95877. };
  95878. var BABYLON;
  95879. (function (BABYLON) {
  95880. /**
  95881. * The effect layer Helps adding post process effect blended with the main pass.
  95882. *
  95883. * This can be for instance use to generate glow or higlight effects on the scene.
  95884. *
  95885. * The effect layer class can not be used directly and is intented to inherited from to be
  95886. * customized per effects.
  95887. */
  95888. var EffectLayer = /** @class */ (function () {
  95889. /**
  95890. * Instantiates a new effect Layer and references it in the scene.
  95891. * @param name The name of the layer
  95892. * @param scene The scene to use the layer in
  95893. */
  95894. function EffectLayer(
  95895. /** The Friendly of the effect in the scene */
  95896. name, scene) {
  95897. this._vertexBuffers = {};
  95898. this._maxSize = 0;
  95899. this._mainTextureDesiredSize = { width: 0, height: 0 };
  95900. this._shouldRender = true;
  95901. this._postProcesses = [];
  95902. this._textures = [];
  95903. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  95904. /**
  95905. * The clear color of the texture used to generate the glow map.
  95906. */
  95907. this.neutralColor = new BABYLON.Color4();
  95908. /**
  95909. * Specifies wether the highlight layer is enabled or not.
  95910. */
  95911. this.isEnabled = true;
  95912. /**
  95913. * An event triggered when the effect layer has been disposed.
  95914. */
  95915. this.onDisposeObservable = new BABYLON.Observable();
  95916. /**
  95917. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  95918. */
  95919. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  95920. /**
  95921. * An event triggered when the generated texture is being merged in the scene.
  95922. */
  95923. this.onBeforeComposeObservable = new BABYLON.Observable();
  95924. /**
  95925. * An event triggered when the generated texture has been merged in the scene.
  95926. */
  95927. this.onAfterComposeObservable = new BABYLON.Observable();
  95928. /**
  95929. * An event triggered when the efffect layer changes its size.
  95930. */
  95931. this.onSizeChangedObservable = new BABYLON.Observable();
  95932. this.name = name;
  95933. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95934. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  95935. if (!component) {
  95936. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  95937. this._scene._addComponent(component);
  95938. }
  95939. this._engine = this._scene.getEngine();
  95940. this._maxSize = this._engine.getCaps().maxTextureSize;
  95941. this._scene.effectLayers.push(this);
  95942. // Generate Buffers
  95943. this._generateIndexBuffer();
  95944. this._genrateVertexBuffer();
  95945. }
  95946. Object.defineProperty(EffectLayer.prototype, "camera", {
  95947. /**
  95948. * Gets the camera attached to the layer.
  95949. */
  95950. get: function () {
  95951. return this._effectLayerOptions.camera;
  95952. },
  95953. enumerable: true,
  95954. configurable: true
  95955. });
  95956. /**
  95957. * Initializes the effect layer with the required options.
  95958. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  95959. */
  95960. EffectLayer.prototype._init = function (options) {
  95961. // Adapt options
  95962. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95963. this._setMainTextureSize();
  95964. this._createMainTexture();
  95965. this._createTextureAndPostProcesses();
  95966. this._mergeEffect = this._createMergeEffect();
  95967. };
  95968. /**
  95969. * Generates the index buffer of the full screen quad blending to the main canvas.
  95970. */
  95971. EffectLayer.prototype._generateIndexBuffer = function () {
  95972. // Indices
  95973. var indices = [];
  95974. indices.push(0);
  95975. indices.push(1);
  95976. indices.push(2);
  95977. indices.push(0);
  95978. indices.push(2);
  95979. indices.push(3);
  95980. this._indexBuffer = this._engine.createIndexBuffer(indices);
  95981. };
  95982. /**
  95983. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  95984. */
  95985. EffectLayer.prototype._genrateVertexBuffer = function () {
  95986. // VBO
  95987. var vertices = [];
  95988. vertices.push(1, 1);
  95989. vertices.push(-1, 1);
  95990. vertices.push(-1, -1);
  95991. vertices.push(1, -1);
  95992. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95993. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  95994. };
  95995. /**
  95996. * Sets the main texture desired size which is the closest power of two
  95997. * of the engine canvas size.
  95998. */
  95999. EffectLayer.prototype._setMainTextureSize = function () {
  96000. if (this._effectLayerOptions.mainTextureFixedSize) {
  96001. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96002. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96003. }
  96004. else {
  96005. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96006. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96007. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96008. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96009. }
  96010. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96011. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96012. };
  96013. /**
  96014. * Creates the main texture for the effect layer.
  96015. */
  96016. EffectLayer.prototype._createMainTexture = function () {
  96017. var _this = this;
  96018. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96019. width: this._mainTextureDesiredSize.width,
  96020. height: this._mainTextureDesiredSize.height
  96021. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96022. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96023. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96024. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96025. this._mainTexture.anisotropicFilteringLevel = 1;
  96026. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96027. this._mainTexture.renderParticles = false;
  96028. this._mainTexture.renderList = null;
  96029. this._mainTexture.ignoreCameraViewport = true;
  96030. // Custom render function
  96031. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96032. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96033. var index;
  96034. var engine = _this._scene.getEngine();
  96035. if (depthOnlySubMeshes.length) {
  96036. engine.setColorWrite(false);
  96037. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96038. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96039. }
  96040. engine.setColorWrite(true);
  96041. }
  96042. for (index = 0; index < opaqueSubMeshes.length; index++) {
  96043. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  96044. }
  96045. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  96046. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  96047. }
  96048. for (index = 0; index < transparentSubMeshes.length; index++) {
  96049. _this._renderSubMesh(transparentSubMeshes.data[index]);
  96050. }
  96051. };
  96052. this._mainTexture.onClearObservable.add(function (engine) {
  96053. engine.clear(_this.neutralColor, true, true, true);
  96054. });
  96055. };
  96056. /**
  96057. * Checks for the readiness of the element composing the layer.
  96058. * @param subMesh the mesh to check for
  96059. * @param useInstances specify wether or not to use instances to render the mesh
  96060. * @param emissiveTexture the associated emissive texture used to generate the glow
  96061. * @return true if ready otherwise, false
  96062. */
  96063. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  96064. var material = subMesh.getMaterial();
  96065. if (!material) {
  96066. return false;
  96067. }
  96068. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  96069. return false;
  96070. }
  96071. var defines = [];
  96072. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96073. var mesh = subMesh.getMesh();
  96074. var uv1 = false;
  96075. var uv2 = false;
  96076. // Alpha test
  96077. if (material && material.needAlphaTesting()) {
  96078. var alphaTexture = material.getAlphaTestTexture();
  96079. if (alphaTexture) {
  96080. defines.push("#define ALPHATEST");
  96081. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96082. alphaTexture.coordinatesIndex === 1) {
  96083. defines.push("#define DIFFUSEUV2");
  96084. uv2 = true;
  96085. }
  96086. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96087. defines.push("#define DIFFUSEUV1");
  96088. uv1 = true;
  96089. }
  96090. }
  96091. }
  96092. // Emissive
  96093. if (emissiveTexture) {
  96094. defines.push("#define EMISSIVE");
  96095. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96096. emissiveTexture.coordinatesIndex === 1) {
  96097. defines.push("#define EMISSIVEUV2");
  96098. uv2 = true;
  96099. }
  96100. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96101. defines.push("#define EMISSIVEUV1");
  96102. uv1 = true;
  96103. }
  96104. }
  96105. if (uv1) {
  96106. attribs.push(BABYLON.VertexBuffer.UVKind);
  96107. defines.push("#define UV1");
  96108. }
  96109. if (uv2) {
  96110. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96111. defines.push("#define UV2");
  96112. }
  96113. // Bones
  96114. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96115. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96116. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96117. if (mesh.numBoneInfluencers > 4) {
  96118. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96119. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96120. }
  96121. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96122. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  96123. }
  96124. else {
  96125. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96126. }
  96127. // Morph targets
  96128. var manager = mesh.morphTargetManager;
  96129. var morphInfluencers = 0;
  96130. if (manager) {
  96131. if (manager.numInfluencers > 0) {
  96132. defines.push("#define MORPHTARGETS");
  96133. morphInfluencers = manager.numInfluencers;
  96134. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  96135. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  96136. }
  96137. }
  96138. // Instances
  96139. if (useInstances) {
  96140. defines.push("#define INSTANCES");
  96141. attribs.push("world0");
  96142. attribs.push("world1");
  96143. attribs.push("world2");
  96144. attribs.push("world3");
  96145. }
  96146. // Get correct effect
  96147. var join = defines.join("\n");
  96148. if (this._cachedDefines !== join) {
  96149. this._cachedDefines = join;
  96150. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  96151. }
  96152. return this._effectLayerMapGenerationEffect.isReady();
  96153. };
  96154. /**
  96155. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  96156. */
  96157. EffectLayer.prototype.render = function () {
  96158. var currentEffect = this._mergeEffect;
  96159. // Check
  96160. if (!currentEffect.isReady())
  96161. return;
  96162. for (var i = 0; i < this._postProcesses.length; i++) {
  96163. if (!this._postProcesses[i].isReady()) {
  96164. return;
  96165. }
  96166. }
  96167. var engine = this._scene.getEngine();
  96168. this.onBeforeComposeObservable.notifyObservers(this);
  96169. // Render
  96170. engine.enableEffect(currentEffect);
  96171. engine.setState(false);
  96172. // VBOs
  96173. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96174. // Cache
  96175. var previousAlphaMode = engine.getAlphaMode();
  96176. // Go Blend.
  96177. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  96178. // Blends the map on the main canvas.
  96179. this._internalRender(currentEffect);
  96180. // Restore Alpha
  96181. engine.setAlphaMode(previousAlphaMode);
  96182. this.onAfterComposeObservable.notifyObservers(this);
  96183. // Handle size changes.
  96184. var size = this._mainTexture.getSize();
  96185. this._setMainTextureSize();
  96186. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  96187. // Recreate RTT and post processes on size change.
  96188. this.onSizeChangedObservable.notifyObservers(this);
  96189. this._disposeTextureAndPostProcesses();
  96190. this._createMainTexture();
  96191. this._createTextureAndPostProcesses();
  96192. }
  96193. };
  96194. /**
  96195. * Determine if a given mesh will be used in the current effect.
  96196. * @param mesh mesh to test
  96197. * @returns true if the mesh will be used
  96198. */
  96199. EffectLayer.prototype.hasMesh = function (mesh) {
  96200. return true;
  96201. };
  96202. /**
  96203. * Returns true if the layer contains information to display, otherwise false.
  96204. * @returns true if the glow layer should be rendered
  96205. */
  96206. EffectLayer.prototype.shouldRender = function () {
  96207. return this.isEnabled && this._shouldRender;
  96208. };
  96209. /**
  96210. * Returns true if the mesh should render, otherwise false.
  96211. * @param mesh The mesh to render
  96212. * @returns true if it should render otherwise false
  96213. */
  96214. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  96215. return true;
  96216. };
  96217. /**
  96218. * Returns true if the mesh should render, otherwise false.
  96219. * @param mesh The mesh to render
  96220. * @returns true if it should render otherwise false
  96221. */
  96222. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  96223. return true;
  96224. };
  96225. /**
  96226. * Renders the submesh passed in parameter to the generation map.
  96227. */
  96228. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  96229. var _this = this;
  96230. if (!this.shouldRender()) {
  96231. return;
  96232. }
  96233. var material = subMesh.getMaterial();
  96234. var mesh = subMesh.getRenderingMesh();
  96235. var scene = this._scene;
  96236. var engine = scene.getEngine();
  96237. if (!material) {
  96238. return;
  96239. }
  96240. // Do not block in blend mode.
  96241. if (material.needAlphaBlendingForMesh(mesh)) {
  96242. return;
  96243. }
  96244. // Culling
  96245. engine.setState(material.backFaceCulling);
  96246. // Managing instances
  96247. var batch = mesh._getInstancesRenderList(subMesh._id);
  96248. if (batch.mustReturn) {
  96249. return;
  96250. }
  96251. // Early Exit per mesh
  96252. if (!this._shouldRenderMesh(mesh)) {
  96253. return;
  96254. }
  96255. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96256. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  96257. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  96258. engine.enableEffect(this._effectLayerMapGenerationEffect);
  96259. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  96260. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  96261. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  96262. // Alpha test
  96263. if (material && material.needAlphaTesting()) {
  96264. var alphaTexture = material.getAlphaTestTexture();
  96265. if (alphaTexture) {
  96266. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  96267. var textureMatrix = alphaTexture.getTextureMatrix();
  96268. if (textureMatrix) {
  96269. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  96270. }
  96271. }
  96272. }
  96273. // Glow emissive only
  96274. if (this._emissiveTextureAndColor.texture) {
  96275. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  96276. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  96277. }
  96278. // Bones
  96279. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96280. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96281. }
  96282. // Morph targets
  96283. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  96284. // Draw
  96285. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  96286. }
  96287. else {
  96288. // Need to reset refresh rate of the main map
  96289. this._mainTexture.resetRefreshCounter();
  96290. }
  96291. };
  96292. /**
  96293. * Rebuild the required buffers.
  96294. * @hidden Internal use only.
  96295. */
  96296. EffectLayer.prototype._rebuild = function () {
  96297. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96298. if (vb) {
  96299. vb._rebuild();
  96300. }
  96301. this._generateIndexBuffer();
  96302. };
  96303. /**
  96304. * Dispose only the render target textures and post process.
  96305. */
  96306. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  96307. this._mainTexture.dispose();
  96308. for (var i = 0; i < this._postProcesses.length; i++) {
  96309. if (this._postProcesses[i]) {
  96310. this._postProcesses[i].dispose();
  96311. }
  96312. }
  96313. this._postProcesses = [];
  96314. for (var i = 0; i < this._textures.length; i++) {
  96315. if (this._textures[i]) {
  96316. this._textures[i].dispose();
  96317. }
  96318. }
  96319. this._textures = [];
  96320. };
  96321. /**
  96322. * Dispose the highlight layer and free resources.
  96323. */
  96324. EffectLayer.prototype.dispose = function () {
  96325. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96326. if (vertexBuffer) {
  96327. vertexBuffer.dispose();
  96328. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96329. }
  96330. if (this._indexBuffer) {
  96331. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96332. this._indexBuffer = null;
  96333. }
  96334. // Clean textures and post processes
  96335. this._disposeTextureAndPostProcesses();
  96336. // Remove from scene
  96337. var index = this._scene.effectLayers.indexOf(this, 0);
  96338. if (index > -1) {
  96339. this._scene.effectLayers.splice(index, 1);
  96340. }
  96341. // Callback
  96342. this.onDisposeObservable.notifyObservers(this);
  96343. this.onDisposeObservable.clear();
  96344. this.onBeforeRenderMainTextureObservable.clear();
  96345. this.onBeforeComposeObservable.clear();
  96346. this.onAfterComposeObservable.clear();
  96347. this.onSizeChangedObservable.clear();
  96348. };
  96349. /**
  96350. * Gets the class name of the effect layer
  96351. * @returns the string with the class name of the effect layer
  96352. */
  96353. EffectLayer.prototype.getClassName = function () {
  96354. return "EffectLayer";
  96355. };
  96356. /**
  96357. * Creates an effect layer from parsed effect layer data
  96358. * @param parsedEffectLayer defines effect layer data
  96359. * @param scene defines the current scene
  96360. * @param rootUrl defines the root URL containing the effect layer information
  96361. * @returns a parsed effect Layer
  96362. */
  96363. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  96364. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  96365. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  96366. };
  96367. __decorate([
  96368. BABYLON.serialize()
  96369. ], EffectLayer.prototype, "name", void 0);
  96370. __decorate([
  96371. BABYLON.serializeAsColor4()
  96372. ], EffectLayer.prototype, "neutralColor", void 0);
  96373. __decorate([
  96374. BABYLON.serialize()
  96375. ], EffectLayer.prototype, "isEnabled", void 0);
  96376. __decorate([
  96377. BABYLON.serializeAsCameraReference()
  96378. ], EffectLayer.prototype, "camera", null);
  96379. return EffectLayer;
  96380. }());
  96381. BABYLON.EffectLayer = EffectLayer;
  96382. })(BABYLON || (BABYLON = {}));
  96383. //# sourceMappingURL=babylon.effectLayer.js.map
  96384. var BABYLON;
  96385. (function (BABYLON) {
  96386. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  96387. for (var index = 0; index < this.effectLayers.length; index++) {
  96388. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  96389. return this.effectLayers[index];
  96390. }
  96391. }
  96392. return null;
  96393. };
  96394. /**
  96395. * Special Glow Blur post process only blurring the alpha channel
  96396. * It enforces keeping the most luminous color in the color channel.
  96397. */
  96398. var GlowBlurPostProcess = /** @class */ (function (_super) {
  96399. __extends(GlowBlurPostProcess, _super);
  96400. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  96401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  96402. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  96403. _this.direction = direction;
  96404. _this.kernel = kernel;
  96405. _this.onApplyObservable.add(function (effect) {
  96406. effect.setFloat2("screenSize", _this.width, _this.height);
  96407. effect.setVector2("direction", _this.direction);
  96408. effect.setFloat("blurWidth", _this.kernel);
  96409. });
  96410. return _this;
  96411. }
  96412. return GlowBlurPostProcess;
  96413. }(BABYLON.PostProcess));
  96414. /**
  96415. * The highlight layer Helps adding a glow effect around a mesh.
  96416. *
  96417. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96418. * glowy meshes to your scene.
  96419. *
  96420. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  96421. */
  96422. var HighlightLayer = /** @class */ (function (_super) {
  96423. __extends(HighlightLayer, _super);
  96424. /**
  96425. * Instantiates a new highlight Layer and references it to the scene..
  96426. * @param name The name of the layer
  96427. * @param scene The scene to use the layer in
  96428. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  96429. */
  96430. function HighlightLayer(name, scene, options) {
  96431. var _this = _super.call(this, name, scene) || this;
  96432. _this.name = name;
  96433. /**
  96434. * Specifies whether or not the inner glow is ACTIVE in the layer.
  96435. */
  96436. _this.innerGlow = true;
  96437. /**
  96438. * Specifies whether or not the outer glow is ACTIVE in the layer.
  96439. */
  96440. _this.outerGlow = true;
  96441. /**
  96442. * An event triggered when the highlight layer is being blurred.
  96443. */
  96444. _this.onBeforeBlurObservable = new BABYLON.Observable();
  96445. /**
  96446. * An event triggered when the highlight layer has been blurred.
  96447. */
  96448. _this.onAfterBlurObservable = new BABYLON.Observable();
  96449. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  96450. _this._meshes = {};
  96451. _this._excludedMeshes = {};
  96452. _this.neutralColor = HighlightLayer.NeutralColor;
  96453. // Warn on stencil
  96454. if (!_this._engine.isStencilEnable) {
  96455. 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 }");
  96456. }
  96457. // Adapt options
  96458. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  96459. // Initialize the layer
  96460. _this._init({
  96461. alphaBlendingMode: _this._options.alphaBlendingMode,
  96462. camera: _this._options.camera,
  96463. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96464. mainTextureRatio: _this._options.mainTextureRatio
  96465. });
  96466. // Do not render as long as no meshes have been added
  96467. _this._shouldRender = false;
  96468. return _this;
  96469. }
  96470. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  96471. /**
  96472. * Gets the horizontal size of the blur.
  96473. */
  96474. get: function () {
  96475. return this._horizontalBlurPostprocess.kernel;
  96476. },
  96477. /**
  96478. * Specifies the horizontal size of the blur.
  96479. */
  96480. set: function (value) {
  96481. this._horizontalBlurPostprocess.kernel = value;
  96482. },
  96483. enumerable: true,
  96484. configurable: true
  96485. });
  96486. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  96487. /**
  96488. * Gets the vertical size of the blur.
  96489. */
  96490. get: function () {
  96491. return this._verticalBlurPostprocess.kernel;
  96492. },
  96493. /**
  96494. * Specifies the vertical size of the blur.
  96495. */
  96496. set: function (value) {
  96497. this._verticalBlurPostprocess.kernel = value;
  96498. },
  96499. enumerable: true,
  96500. configurable: true
  96501. });
  96502. /**
  96503. * Get the effect name of the layer.
  96504. * @return The effect name
  96505. */
  96506. HighlightLayer.prototype.getEffectName = function () {
  96507. return HighlightLayer.EffectName;
  96508. };
  96509. /**
  96510. * Create the merge effect. This is the shader use to blit the information back
  96511. * to the main canvas at the end of the scene rendering.
  96512. */
  96513. HighlightLayer.prototype._createMergeEffect = function () {
  96514. // Effect
  96515. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  96516. };
  96517. /**
  96518. * Creates the render target textures and post processes used in the highlight layer.
  96519. */
  96520. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  96521. var _this = this;
  96522. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  96523. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  96524. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96525. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96526. var textureType = 0;
  96527. if (this._engine.getCaps().textureHalfFloatRender) {
  96528. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96529. }
  96530. else {
  96531. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96532. }
  96533. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  96534. width: blurTextureWidth,
  96535. height: blurTextureHeight
  96536. }, this._scene, false, true, textureType);
  96537. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96538. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96539. this._blurTexture.anisotropicFilteringLevel = 16;
  96540. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  96541. this._blurTexture.renderParticles = false;
  96542. this._blurTexture.ignoreCameraViewport = true;
  96543. this._textures = [this._blurTexture];
  96544. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  96545. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96546. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  96547. effect.setTexture("textureSampler", _this._mainTexture);
  96548. });
  96549. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96550. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96551. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96552. });
  96553. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96554. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  96555. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96556. });
  96557. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96558. }
  96559. else {
  96560. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  96561. width: blurTextureWidth,
  96562. height: blurTextureHeight
  96563. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96564. this._horizontalBlurPostprocess.width = blurTextureWidth;
  96565. this._horizontalBlurPostprocess.height = blurTextureHeight;
  96566. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96567. effect.setTexture("textureSampler", _this._mainTexture);
  96568. });
  96569. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  96570. width: blurTextureWidth,
  96571. height: blurTextureHeight
  96572. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96573. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96574. }
  96575. this._mainTexture.onAfterUnbindObservable.add(function () {
  96576. _this.onBeforeBlurObservable.notifyObservers(_this);
  96577. var internalTexture = _this._blurTexture.getInternalTexture();
  96578. if (internalTexture) {
  96579. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  96580. }
  96581. _this.onAfterBlurObservable.notifyObservers(_this);
  96582. });
  96583. // Prevent autoClear.
  96584. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96585. };
  96586. /**
  96587. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96588. */
  96589. HighlightLayer.prototype.needStencil = function () {
  96590. return true;
  96591. };
  96592. /**
  96593. * Checks for the readiness of the element composing the layer.
  96594. * @param subMesh the mesh to check for
  96595. * @param useInstances specify wether or not to use instances to render the mesh
  96596. * @param emissiveTexture the associated emissive texture used to generate the glow
  96597. * @return true if ready otherwise, false
  96598. */
  96599. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  96600. var material = subMesh.getMaterial();
  96601. var mesh = subMesh.getRenderingMesh();
  96602. if (!material || !mesh || !this._meshes) {
  96603. return false;
  96604. }
  96605. var emissiveTexture = null;
  96606. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96607. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96608. emissiveTexture = material.emissiveTexture;
  96609. }
  96610. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96611. };
  96612. /**
  96613. * Implementation specific of rendering the generating effect on the main canvas.
  96614. * @param effect The effect used to render through
  96615. */
  96616. HighlightLayer.prototype._internalRender = function (effect) {
  96617. // Texture
  96618. effect.setTexture("textureSampler", this._blurTexture);
  96619. // Cache
  96620. var engine = this._engine;
  96621. var previousStencilBuffer = engine.getStencilBuffer();
  96622. var previousStencilFunction = engine.getStencilFunction();
  96623. var previousStencilMask = engine.getStencilMask();
  96624. var previousStencilOperationPass = engine.getStencilOperationPass();
  96625. var previousStencilOperationFail = engine.getStencilOperationFail();
  96626. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  96627. var previousStencilReference = engine.getStencilFunctionReference();
  96628. // Stencil operations
  96629. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  96630. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  96631. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  96632. // Draw order
  96633. engine.setStencilMask(0x00);
  96634. engine.setStencilBuffer(true);
  96635. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  96636. // 2 passes inner outer
  96637. if (this.outerGlow) {
  96638. effect.setFloat("offset", 0);
  96639. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  96640. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96641. }
  96642. if (this.innerGlow) {
  96643. effect.setFloat("offset", 1);
  96644. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  96645. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96646. }
  96647. // Restore Cache
  96648. engine.setStencilFunction(previousStencilFunction);
  96649. engine.setStencilMask(previousStencilMask);
  96650. engine.setStencilBuffer(previousStencilBuffer);
  96651. engine.setStencilOperationPass(previousStencilOperationPass);
  96652. engine.setStencilOperationFail(previousStencilOperationFail);
  96653. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  96654. engine.setStencilFunctionReference(previousStencilReference);
  96655. };
  96656. /**
  96657. * Returns true if the layer contains information to display, otherwise false.
  96658. */
  96659. HighlightLayer.prototype.shouldRender = function () {
  96660. if (_super.prototype.shouldRender.call(this)) {
  96661. return this._meshes ? true : false;
  96662. }
  96663. return false;
  96664. };
  96665. /**
  96666. * Returns true if the mesh should render, otherwise false.
  96667. * @param mesh The mesh to render
  96668. * @returns true if it should render otherwise false
  96669. */
  96670. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  96671. // Excluded Mesh
  96672. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  96673. return false;
  96674. }
  96675. ;
  96676. return true;
  96677. };
  96678. /**
  96679. * Sets the required values for both the emissive texture and and the main color.
  96680. */
  96681. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96682. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96683. if (highlightLayerMesh) {
  96684. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  96685. }
  96686. else {
  96687. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96688. }
  96689. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96690. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96691. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  96692. }
  96693. else {
  96694. this._emissiveTextureAndColor.texture = null;
  96695. }
  96696. };
  96697. /**
  96698. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  96699. * @param mesh The mesh to exclude from the highlight layer
  96700. */
  96701. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  96702. if (!this._excludedMeshes) {
  96703. return;
  96704. }
  96705. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96706. if (!meshExcluded) {
  96707. this._excludedMeshes[mesh.uniqueId] = {
  96708. mesh: mesh,
  96709. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  96710. mesh.getEngine().setStencilBuffer(false);
  96711. }),
  96712. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  96713. mesh.getEngine().setStencilBuffer(true);
  96714. }),
  96715. };
  96716. }
  96717. };
  96718. /**
  96719. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  96720. * @param mesh The mesh to highlight
  96721. */
  96722. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  96723. if (!this._excludedMeshes) {
  96724. return;
  96725. }
  96726. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96727. if (meshExcluded) {
  96728. if (meshExcluded.beforeRender) {
  96729. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  96730. }
  96731. if (meshExcluded.afterRender) {
  96732. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  96733. }
  96734. }
  96735. this._excludedMeshes[mesh.uniqueId] = null;
  96736. };
  96737. /**
  96738. * Determine if a given mesh will be highlighted by the current HighlightLayer
  96739. * @param mesh mesh to test
  96740. * @returns true if the mesh will be highlighted by the current HighlightLayer
  96741. */
  96742. HighlightLayer.prototype.hasMesh = function (mesh) {
  96743. if (!this._meshes) {
  96744. return false;
  96745. }
  96746. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  96747. };
  96748. /**
  96749. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  96750. * @param mesh The mesh to highlight
  96751. * @param color The color of the highlight
  96752. * @param glowEmissiveOnly Extract the glow from the emissive texture
  96753. */
  96754. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  96755. var _this = this;
  96756. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  96757. if (!this._meshes) {
  96758. return;
  96759. }
  96760. var meshHighlight = this._meshes[mesh.uniqueId];
  96761. if (meshHighlight) {
  96762. meshHighlight.color = color;
  96763. }
  96764. else {
  96765. this._meshes[mesh.uniqueId] = {
  96766. mesh: mesh,
  96767. color: color,
  96768. // Lambda required for capture due to Observable this context
  96769. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  96770. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  96771. _this._defaultStencilReference(mesh);
  96772. }
  96773. else {
  96774. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  96775. }
  96776. }),
  96777. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  96778. glowEmissiveOnly: glowEmissiveOnly
  96779. };
  96780. mesh.onDisposeObservable.add(function () {
  96781. _this._disposeMesh(mesh);
  96782. });
  96783. }
  96784. this._shouldRender = true;
  96785. };
  96786. /**
  96787. * Remove a mesh from the highlight layer in order to make it stop glowing.
  96788. * @param mesh The mesh to highlight
  96789. */
  96790. HighlightLayer.prototype.removeMesh = function (mesh) {
  96791. if (!this._meshes) {
  96792. return;
  96793. }
  96794. var meshHighlight = this._meshes[mesh.uniqueId];
  96795. if (meshHighlight) {
  96796. if (meshHighlight.observerHighlight) {
  96797. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96798. }
  96799. if (meshHighlight.observerDefault) {
  96800. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96801. }
  96802. delete this._meshes[mesh.uniqueId];
  96803. }
  96804. this._shouldRender = false;
  96805. for (var meshHighlightToCheck in this._meshes) {
  96806. if (this._meshes[meshHighlightToCheck]) {
  96807. this._shouldRender = true;
  96808. break;
  96809. }
  96810. }
  96811. };
  96812. /**
  96813. * Force the stencil to the normal expected value for none glowing parts
  96814. */
  96815. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  96816. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  96817. };
  96818. /**
  96819. * Free any resources and references associated to a mesh.
  96820. * Internal use
  96821. * @param mesh The mesh to free.
  96822. */
  96823. HighlightLayer.prototype._disposeMesh = function (mesh) {
  96824. this.removeMesh(mesh);
  96825. this.removeExcludedMesh(mesh);
  96826. };
  96827. /**
  96828. * Dispose the highlight layer and free resources.
  96829. */
  96830. HighlightLayer.prototype.dispose = function () {
  96831. if (this._meshes) {
  96832. // Clean mesh references
  96833. for (var id in this._meshes) {
  96834. var meshHighlight = this._meshes[id];
  96835. if (meshHighlight && meshHighlight.mesh) {
  96836. if (meshHighlight.observerHighlight) {
  96837. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96838. }
  96839. if (meshHighlight.observerDefault) {
  96840. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96841. }
  96842. }
  96843. }
  96844. this._meshes = null;
  96845. }
  96846. if (this._excludedMeshes) {
  96847. for (var id in this._excludedMeshes) {
  96848. var meshHighlight = this._excludedMeshes[id];
  96849. if (meshHighlight) {
  96850. if (meshHighlight.beforeRender) {
  96851. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  96852. }
  96853. if (meshHighlight.afterRender) {
  96854. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  96855. }
  96856. }
  96857. }
  96858. this._excludedMeshes = null;
  96859. }
  96860. _super.prototype.dispose.call(this);
  96861. };
  96862. /**
  96863. * Gets the class name of the effect layer
  96864. * @returns the string with the class name of the effect layer
  96865. */
  96866. HighlightLayer.prototype.getClassName = function () {
  96867. return "HighlightLayer";
  96868. };
  96869. /**
  96870. * Serializes this Highlight layer
  96871. * @returns a serialized Highlight layer object
  96872. */
  96873. HighlightLayer.prototype.serialize = function () {
  96874. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96875. serializationObject.customType = "BABYLON.HighlightLayer";
  96876. // Highlighted meshes
  96877. serializationObject.meshes = [];
  96878. if (this._meshes) {
  96879. for (var m in this._meshes) {
  96880. var mesh = this._meshes[m];
  96881. if (mesh) {
  96882. serializationObject.meshes.push({
  96883. glowEmissiveOnly: mesh.glowEmissiveOnly,
  96884. color: mesh.color.asArray(),
  96885. meshId: mesh.mesh.id
  96886. });
  96887. }
  96888. }
  96889. }
  96890. // Excluded meshes
  96891. serializationObject.excludedMeshes = [];
  96892. if (this._excludedMeshes) {
  96893. for (var e in this._excludedMeshes) {
  96894. var excludedMesh = this._excludedMeshes[e];
  96895. if (excludedMesh) {
  96896. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  96897. }
  96898. }
  96899. }
  96900. return serializationObject;
  96901. };
  96902. /**
  96903. * Creates a Highlight layer from parsed Highlight layer data
  96904. * @param parsedHightlightLayer defines the Highlight layer data
  96905. * @param scene defines the current scene
  96906. * @param rootUrl defines the root URL containing the Highlight layer information
  96907. * @returns a parsed Highlight layer
  96908. */
  96909. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  96910. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  96911. var index;
  96912. // Excluded meshes
  96913. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  96914. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  96915. if (mesh) {
  96916. hl.addExcludedMesh(mesh);
  96917. }
  96918. }
  96919. // Included meshes
  96920. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  96921. var highlightedMesh = parsedHightlightLayer.meshes[index];
  96922. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  96923. if (mesh) {
  96924. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  96925. }
  96926. }
  96927. return hl;
  96928. };
  96929. /**
  96930. * Effect Name of the highlight layer.
  96931. */
  96932. HighlightLayer.EffectName = "HighlightLayer";
  96933. /**
  96934. * The neutral color used during the preparation of the glow effect.
  96935. * This is black by default as the blend operation is a blend operation.
  96936. */
  96937. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  96938. /**
  96939. * Stencil value used for glowing meshes.
  96940. */
  96941. HighlightLayer.GlowingMeshStencilReference = 0x02;
  96942. /**
  96943. * Stencil value used for the other meshes in the scene.
  96944. */
  96945. HighlightLayer.NormalMeshStencilReference = 0x01;
  96946. __decorate([
  96947. BABYLON.serialize()
  96948. ], HighlightLayer.prototype, "innerGlow", void 0);
  96949. __decorate([
  96950. BABYLON.serialize()
  96951. ], HighlightLayer.prototype, "outerGlow", void 0);
  96952. __decorate([
  96953. BABYLON.serialize()
  96954. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  96955. __decorate([
  96956. BABYLON.serialize()
  96957. ], HighlightLayer.prototype, "blurVerticalSize", null);
  96958. __decorate([
  96959. BABYLON.serialize("options")
  96960. ], HighlightLayer.prototype, "_options", void 0);
  96961. return HighlightLayer;
  96962. }(BABYLON.EffectLayer));
  96963. BABYLON.HighlightLayer = HighlightLayer;
  96964. })(BABYLON || (BABYLON = {}));
  96965. //# sourceMappingURL=babylon.highlightLayer.js.map
  96966. var BABYLON;
  96967. (function (BABYLON) {
  96968. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  96969. for (var index = 0; index < this.effectLayers.length; index++) {
  96970. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  96971. return this.effectLayers[index];
  96972. }
  96973. }
  96974. return null;
  96975. };
  96976. /**
  96977. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  96978. *
  96979. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96980. * glowy meshes to your scene.
  96981. *
  96982. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  96983. */
  96984. var GlowLayer = /** @class */ (function (_super) {
  96985. __extends(GlowLayer, _super);
  96986. /**
  96987. * Instantiates a new glow Layer and references it to the scene.
  96988. * @param name The name of the layer
  96989. * @param scene The scene to use the layer in
  96990. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  96991. */
  96992. function GlowLayer(name, scene, options) {
  96993. var _this = _super.call(this, name, scene) || this;
  96994. _this._intensity = 1.0;
  96995. _this._includedOnlyMeshes = [];
  96996. _this._excludedMeshes = [];
  96997. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  96998. // Adapt options
  96999. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  97000. // Initialize the layer
  97001. _this._init({
  97002. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97003. camera: _this._options.camera,
  97004. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97005. mainTextureRatio: _this._options.mainTextureRatio
  97006. });
  97007. return _this;
  97008. }
  97009. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97010. /**
  97011. * Gets the kernel size of the blur.
  97012. */
  97013. get: function () {
  97014. return this._horizontalBlurPostprocess1.kernel;
  97015. },
  97016. /**
  97017. * Sets the kernel size of the blur.
  97018. */
  97019. set: function (value) {
  97020. this._horizontalBlurPostprocess1.kernel = value;
  97021. this._verticalBlurPostprocess1.kernel = value;
  97022. this._horizontalBlurPostprocess2.kernel = value;
  97023. this._verticalBlurPostprocess2.kernel = value;
  97024. },
  97025. enumerable: true,
  97026. configurable: true
  97027. });
  97028. Object.defineProperty(GlowLayer.prototype, "intensity", {
  97029. /**
  97030. * Gets the glow intensity.
  97031. */
  97032. get: function () {
  97033. return this._intensity;
  97034. },
  97035. /**
  97036. * Sets the glow intensity.
  97037. */
  97038. set: function (value) {
  97039. this._intensity = value;
  97040. },
  97041. enumerable: true,
  97042. configurable: true
  97043. });
  97044. /**
  97045. * Get the effect name of the layer.
  97046. * @return The effect name
  97047. */
  97048. GlowLayer.prototype.getEffectName = function () {
  97049. return GlowLayer.EffectName;
  97050. };
  97051. /**
  97052. * Create the merge effect. This is the shader use to blit the information back
  97053. * to the main canvas at the end of the scene rendering.
  97054. */
  97055. GlowLayer.prototype._createMergeEffect = function () {
  97056. // Effect
  97057. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  97058. };
  97059. /**
  97060. * Creates the render target textures and post processes used in the glow layer.
  97061. */
  97062. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  97063. var _this = this;
  97064. var blurTextureWidth = this._mainTextureDesiredSize.width;
  97065. var blurTextureHeight = this._mainTextureDesiredSize.height;
  97066. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97067. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97068. var textureType = 0;
  97069. if (this._engine.getCaps().textureHalfFloatRender) {
  97070. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97071. }
  97072. else {
  97073. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97074. }
  97075. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  97076. width: blurTextureWidth,
  97077. height: blurTextureHeight
  97078. }, this._scene, false, true, textureType);
  97079. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97080. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97081. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97082. this._blurTexture1.renderParticles = false;
  97083. this._blurTexture1.ignoreCameraViewport = true;
  97084. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  97085. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  97086. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  97087. width: blurTextureWidth2,
  97088. height: blurTextureHeight2
  97089. }, this._scene, false, true, textureType);
  97090. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97091. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97092. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97093. this._blurTexture2.renderParticles = false;
  97094. this._blurTexture2.ignoreCameraViewport = true;
  97095. this._textures = [this._blurTexture1, this._blurTexture2];
  97096. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97097. width: blurTextureWidth,
  97098. height: blurTextureHeight
  97099. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97100. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  97101. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  97102. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  97103. effect.setTexture("textureSampler", _this._mainTexture);
  97104. });
  97105. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97106. width: blurTextureWidth,
  97107. height: blurTextureHeight
  97108. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97109. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97110. width: blurTextureWidth2,
  97111. height: blurTextureHeight2
  97112. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97113. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  97114. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  97115. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  97116. effect.setTexture("textureSampler", _this._blurTexture1);
  97117. });
  97118. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97119. width: blurTextureWidth2,
  97120. height: blurTextureHeight2
  97121. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97122. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97123. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  97124. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97125. this._mainTexture.samples = this._options.mainTextureSamples;
  97126. this._mainTexture.onAfterUnbindObservable.add(function () {
  97127. var internalTexture = _this._blurTexture1.getInternalTexture();
  97128. if (internalTexture) {
  97129. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  97130. internalTexture = _this._blurTexture2.getInternalTexture();
  97131. if (internalTexture) {
  97132. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  97133. }
  97134. }
  97135. });
  97136. // Prevent autoClear.
  97137. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97138. };
  97139. /**
  97140. * Checks for the readiness of the element composing the layer.
  97141. * @param subMesh the mesh to check for
  97142. * @param useInstances specify wether or not to use instances to render the mesh
  97143. * @param emissiveTexture the associated emissive texture used to generate the glow
  97144. * @return true if ready otherwise, false
  97145. */
  97146. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  97147. var material = subMesh.getMaterial();
  97148. var mesh = subMesh.getRenderingMesh();
  97149. if (!material || !mesh) {
  97150. return false;
  97151. }
  97152. var emissiveTexture = material.emissiveTexture;
  97153. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97154. };
  97155. /**
  97156. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97157. */
  97158. GlowLayer.prototype.needStencil = function () {
  97159. return false;
  97160. };
  97161. /**
  97162. * Implementation specific of rendering the generating effect on the main canvas.
  97163. * @param effect The effect used to render through
  97164. */
  97165. GlowLayer.prototype._internalRender = function (effect) {
  97166. // Texture
  97167. effect.setTexture("textureSampler", this._blurTexture1);
  97168. effect.setTexture("textureSampler2", this._blurTexture2);
  97169. effect.setFloat("offset", this._intensity);
  97170. // Cache
  97171. var engine = this._engine;
  97172. var previousStencilBuffer = engine.getStencilBuffer();
  97173. // Draw order
  97174. engine.setStencilBuffer(false);
  97175. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97176. // Draw order
  97177. engine.setStencilBuffer(previousStencilBuffer);
  97178. };
  97179. /**
  97180. * Sets the required values for both the emissive texture and and the main color.
  97181. */
  97182. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97183. var textureLevel = 1.0;
  97184. if (this.customEmissiveTextureSelector) {
  97185. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  97186. }
  97187. else {
  97188. if (material) {
  97189. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97190. if (this._emissiveTextureAndColor.texture) {
  97191. textureLevel = this._emissiveTextureAndColor.texture.level;
  97192. }
  97193. }
  97194. else {
  97195. this._emissiveTextureAndColor.texture = null;
  97196. }
  97197. }
  97198. if (this.customEmissiveColorSelector) {
  97199. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  97200. }
  97201. else {
  97202. if (material.emissiveColor) {
  97203. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  97204. }
  97205. else {
  97206. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97207. }
  97208. }
  97209. };
  97210. /**
  97211. * Returns true if the mesh should render, otherwise false.
  97212. * @param mesh The mesh to render
  97213. * @returns true if it should render otherwise false
  97214. */
  97215. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  97216. return this.hasMesh(mesh);
  97217. };
  97218. /**
  97219. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  97220. * @param mesh The mesh to exclude from the glow layer
  97221. */
  97222. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  97223. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  97224. this._excludedMeshes.push(mesh.uniqueId);
  97225. }
  97226. };
  97227. /**
  97228. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  97229. * @param mesh The mesh to remove
  97230. */
  97231. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  97232. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  97233. if (index !== -1) {
  97234. this._excludedMeshes.splice(index, 1);
  97235. }
  97236. };
  97237. /**
  97238. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  97239. * @param mesh The mesh to include in the glow layer
  97240. */
  97241. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  97242. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  97243. this._includedOnlyMeshes.push(mesh.uniqueId);
  97244. }
  97245. };
  97246. /**
  97247. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  97248. * @param mesh The mesh to remove
  97249. */
  97250. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  97251. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  97252. if (index !== -1) {
  97253. this._includedOnlyMeshes.splice(index, 1);
  97254. }
  97255. };
  97256. /**
  97257. * Determine if a given mesh will be used in the glow layer
  97258. * @param mesh The mesh to test
  97259. * @returns true if the mesh will be highlighted by the current glow layer
  97260. */
  97261. GlowLayer.prototype.hasMesh = function (mesh) {
  97262. // Included Mesh
  97263. if (this._includedOnlyMeshes.length) {
  97264. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  97265. }
  97266. ;
  97267. // Excluded Mesh
  97268. if (this._excludedMeshes.length) {
  97269. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  97270. }
  97271. ;
  97272. return true;
  97273. };
  97274. /**
  97275. * Free any resources and references associated to a mesh.
  97276. * Internal use
  97277. * @param mesh The mesh to free.
  97278. */
  97279. GlowLayer.prototype._disposeMesh = function (mesh) {
  97280. this.removeIncludedOnlyMesh(mesh);
  97281. this.removeExcludedMesh(mesh);
  97282. };
  97283. /**
  97284. * Gets the class name of the effect layer
  97285. * @returns the string with the class name of the effect layer
  97286. */
  97287. GlowLayer.prototype.getClassName = function () {
  97288. return "GlowLayer";
  97289. };
  97290. /**
  97291. * Serializes this glow layer
  97292. * @returns a serialized glow layer object
  97293. */
  97294. GlowLayer.prototype.serialize = function () {
  97295. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97296. serializationObject.customType = "BABYLON.GlowLayer";
  97297. var index;
  97298. // Included meshes
  97299. serializationObject.includedMeshes = [];
  97300. if (this._includedOnlyMeshes.length) {
  97301. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  97302. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  97303. if (mesh) {
  97304. serializationObject.includedMeshes.push(mesh.id);
  97305. }
  97306. }
  97307. }
  97308. // Excluded meshes
  97309. serializationObject.excludedMeshes = [];
  97310. if (this._excludedMeshes.length) {
  97311. for (index = 0; index < this._excludedMeshes.length; index++) {
  97312. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  97313. if (mesh) {
  97314. serializationObject.excludedMeshes.push(mesh.id);
  97315. }
  97316. }
  97317. }
  97318. return serializationObject;
  97319. };
  97320. /**
  97321. * Creates a Glow Layer from parsed glow layer data
  97322. * @param parsedGlowLayer defines glow layer data
  97323. * @param scene defines the current scene
  97324. * @param rootUrl defines the root URL containing the glow layer information
  97325. * @returns a parsed Glow Layer
  97326. */
  97327. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  97328. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  97329. var index;
  97330. // Excluded meshes
  97331. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  97332. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  97333. if (mesh) {
  97334. gl.addExcludedMesh(mesh);
  97335. }
  97336. }
  97337. // Included meshes
  97338. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  97339. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  97340. if (mesh) {
  97341. gl.addIncludedOnlyMesh(mesh);
  97342. }
  97343. }
  97344. return gl;
  97345. };
  97346. /**
  97347. * Effect Name of the layer.
  97348. */
  97349. GlowLayer.EffectName = "GlowLayer";
  97350. /**
  97351. * The default blur kernel size used for the glow.
  97352. */
  97353. GlowLayer.DefaultBlurKernelSize = 32;
  97354. /**
  97355. * The default texture size ratio used for the glow.
  97356. */
  97357. GlowLayer.DefaultTextureRatio = 0.5;
  97358. __decorate([
  97359. BABYLON.serialize()
  97360. ], GlowLayer.prototype, "blurKernelSize", null);
  97361. __decorate([
  97362. BABYLON.serialize()
  97363. ], GlowLayer.prototype, "intensity", null);
  97364. __decorate([
  97365. BABYLON.serialize("options")
  97366. ], GlowLayer.prototype, "_options", void 0);
  97367. return GlowLayer;
  97368. }(BABYLON.EffectLayer));
  97369. BABYLON.GlowLayer = GlowLayer;
  97370. })(BABYLON || (BABYLON = {}));
  97371. //# sourceMappingURL=babylon.glowLayer.js.map
  97372. var BABYLON;
  97373. (function (BABYLON) {
  97374. /**
  97375. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  97376. */
  97377. var AssetTaskState;
  97378. (function (AssetTaskState) {
  97379. /**
  97380. * Initialization
  97381. */
  97382. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  97383. /**
  97384. * Running
  97385. */
  97386. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  97387. /**
  97388. * Done
  97389. */
  97390. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  97391. /**
  97392. * Error
  97393. */
  97394. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  97395. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  97396. /**
  97397. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  97398. */
  97399. var AbstractAssetTask = /** @class */ (function () {
  97400. /**
  97401. * Creates a new {BABYLON.AssetsManager}
  97402. * @param name defines the name of the task
  97403. */
  97404. function AbstractAssetTask(
  97405. /**
  97406. * Task name
  97407. */ name) {
  97408. this.name = name;
  97409. this._isCompleted = false;
  97410. this._taskState = AssetTaskState.INIT;
  97411. }
  97412. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  97413. /**
  97414. * Get if the task is completed
  97415. */
  97416. get: function () {
  97417. return this._isCompleted;
  97418. },
  97419. enumerable: true,
  97420. configurable: true
  97421. });
  97422. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  97423. /**
  97424. * Gets the current state of the task
  97425. */
  97426. get: function () {
  97427. return this._taskState;
  97428. },
  97429. enumerable: true,
  97430. configurable: true
  97431. });
  97432. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  97433. /**
  97434. * Gets the current error object (if task is in error)
  97435. */
  97436. get: function () {
  97437. return this._errorObject;
  97438. },
  97439. enumerable: true,
  97440. configurable: true
  97441. });
  97442. /**
  97443. * Internal only
  97444. * @hidden
  97445. */
  97446. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  97447. if (this._errorObject) {
  97448. return;
  97449. }
  97450. this._errorObject = {
  97451. message: message,
  97452. exception: exception
  97453. };
  97454. };
  97455. /**
  97456. * Execute the current task
  97457. * @param scene defines the scene where you want your assets to be loaded
  97458. * @param onSuccess is a callback called when the task is successfully executed
  97459. * @param onError is a callback called if an error occurs
  97460. */
  97461. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97462. var _this = this;
  97463. this._taskState = AssetTaskState.RUNNING;
  97464. this.runTask(scene, function () {
  97465. _this.onDoneCallback(onSuccess, onError);
  97466. }, function (msg, exception) {
  97467. _this.onErrorCallback(onError, msg, exception);
  97468. });
  97469. };
  97470. /**
  97471. * Execute the current task
  97472. * @param scene defines the scene where you want your assets to be loaded
  97473. * @param onSuccess is a callback called when the task is successfully executed
  97474. * @param onError is a callback called if an error occurs
  97475. */
  97476. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97477. throw new Error("runTask is not implemented");
  97478. };
  97479. /**
  97480. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  97481. * This can be used with failed tasks that have the reason for failure fixed.
  97482. */
  97483. AbstractAssetTask.prototype.reset = function () {
  97484. this._taskState = AssetTaskState.INIT;
  97485. };
  97486. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  97487. this._taskState = AssetTaskState.ERROR;
  97488. this._errorObject = {
  97489. message: message,
  97490. exception: exception
  97491. };
  97492. if (this.onError) {
  97493. this.onError(this, message, exception);
  97494. }
  97495. onError();
  97496. };
  97497. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  97498. try {
  97499. this._taskState = AssetTaskState.DONE;
  97500. this._isCompleted = true;
  97501. if (this.onSuccess) {
  97502. this.onSuccess(this);
  97503. }
  97504. onSuccess();
  97505. }
  97506. catch (e) {
  97507. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  97508. }
  97509. };
  97510. return AbstractAssetTask;
  97511. }());
  97512. BABYLON.AbstractAssetTask = AbstractAssetTask;
  97513. /**
  97514. * Class used to share progress information about assets loading
  97515. */
  97516. var AssetsProgressEvent = /** @class */ (function () {
  97517. /**
  97518. * Creates a {BABYLON.AssetsProgressEvent}
  97519. * @param remainingCount defines the number of remaining tasks to process
  97520. * @param totalCount defines the total number of tasks
  97521. * @param task defines the task that was just processed
  97522. */
  97523. function AssetsProgressEvent(remainingCount, totalCount, task) {
  97524. this.remainingCount = remainingCount;
  97525. this.totalCount = totalCount;
  97526. this.task = task;
  97527. }
  97528. return AssetsProgressEvent;
  97529. }());
  97530. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  97531. /**
  97532. * Define a task used by {BABYLON.AssetsManager} to load meshes
  97533. */
  97534. var MeshAssetTask = /** @class */ (function (_super) {
  97535. __extends(MeshAssetTask, _super);
  97536. /**
  97537. * Creates a new {BABYLON.MeshAssetTask}
  97538. * @param name defines the name of the task
  97539. * @param meshesNames defines the list of mesh's names you want to load
  97540. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  97541. * @param sceneFilename defines the filename of the scene to load from
  97542. */
  97543. function MeshAssetTask(
  97544. /**
  97545. * Defines the name of the task
  97546. */
  97547. name,
  97548. /**
  97549. * Defines the list of mesh's names you want to load
  97550. */
  97551. meshesNames,
  97552. /**
  97553. * Defines the root url to use as a base to load your meshes and associated resources
  97554. */
  97555. rootUrl,
  97556. /**
  97557. * Defines the filename of the scene to load from
  97558. */
  97559. sceneFilename) {
  97560. var _this = _super.call(this, name) || this;
  97561. _this.name = name;
  97562. _this.meshesNames = meshesNames;
  97563. _this.rootUrl = rootUrl;
  97564. _this.sceneFilename = sceneFilename;
  97565. return _this;
  97566. }
  97567. /**
  97568. * Execute the current task
  97569. * @param scene defines the scene where you want your assets to be loaded
  97570. * @param onSuccess is a callback called when the task is successfully executed
  97571. * @param onError is a callback called if an error occurs
  97572. */
  97573. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97574. var _this = this;
  97575. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  97576. _this.loadedMeshes = meshes;
  97577. _this.loadedParticleSystems = particleSystems;
  97578. _this.loadedSkeletons = skeletons;
  97579. onSuccess();
  97580. }, null, function (scene, message, exception) {
  97581. onError(message, exception);
  97582. });
  97583. };
  97584. return MeshAssetTask;
  97585. }(AbstractAssetTask));
  97586. BABYLON.MeshAssetTask = MeshAssetTask;
  97587. /**
  97588. * Define a task used by {BABYLON.AssetsManager} to load text content
  97589. */
  97590. var TextFileAssetTask = /** @class */ (function (_super) {
  97591. __extends(TextFileAssetTask, _super);
  97592. /**
  97593. * Creates a new TextFileAssetTask object
  97594. * @param name defines the name of the task
  97595. * @param url defines the location of the file to load
  97596. */
  97597. function TextFileAssetTask(
  97598. /**
  97599. * Defines the name of the task
  97600. */
  97601. name,
  97602. /**
  97603. * Defines the location of the file to load
  97604. */
  97605. url) {
  97606. var _this = _super.call(this, name) || this;
  97607. _this.name = name;
  97608. _this.url = url;
  97609. return _this;
  97610. }
  97611. /**
  97612. * Execute the current task
  97613. * @param scene defines the scene where you want your assets to be loaded
  97614. * @param onSuccess is a callback called when the task is successfully executed
  97615. * @param onError is a callback called if an error occurs
  97616. */
  97617. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97618. var _this = this;
  97619. scene._loadFile(this.url, function (data) {
  97620. _this.text = data;
  97621. onSuccess();
  97622. }, undefined, false, false, function (request, exception) {
  97623. if (request) {
  97624. onError(request.status + " " + request.statusText, exception);
  97625. }
  97626. });
  97627. };
  97628. return TextFileAssetTask;
  97629. }(AbstractAssetTask));
  97630. BABYLON.TextFileAssetTask = TextFileAssetTask;
  97631. /**
  97632. * Define a task used by {BABYLON.AssetsManager} to load binary data
  97633. */
  97634. var BinaryFileAssetTask = /** @class */ (function (_super) {
  97635. __extends(BinaryFileAssetTask, _super);
  97636. /**
  97637. * Creates a new BinaryFileAssetTask object
  97638. * @param name defines the name of the new task
  97639. * @param url defines the location of the file to load
  97640. */
  97641. function BinaryFileAssetTask(
  97642. /**
  97643. * Defines the name of the task
  97644. */
  97645. name,
  97646. /**
  97647. * Defines the location of the file to load
  97648. */
  97649. url) {
  97650. var _this = _super.call(this, name) || this;
  97651. _this.name = name;
  97652. _this.url = url;
  97653. return _this;
  97654. }
  97655. /**
  97656. * Execute the current task
  97657. * @param scene defines the scene where you want your assets to be loaded
  97658. * @param onSuccess is a callback called when the task is successfully executed
  97659. * @param onError is a callback called if an error occurs
  97660. */
  97661. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97662. var _this = this;
  97663. scene._loadFile(this.url, function (data) {
  97664. _this.data = data;
  97665. onSuccess();
  97666. }, undefined, true, true, function (request, exception) {
  97667. if (request) {
  97668. onError(request.status + " " + request.statusText, exception);
  97669. }
  97670. });
  97671. };
  97672. return BinaryFileAssetTask;
  97673. }(AbstractAssetTask));
  97674. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  97675. /**
  97676. * Define a task used by {BABYLON.AssetsManager} to load images
  97677. */
  97678. var ImageAssetTask = /** @class */ (function (_super) {
  97679. __extends(ImageAssetTask, _super);
  97680. /**
  97681. * Creates a new ImageAssetTask
  97682. * @param name defines the name of the task
  97683. * @param url defines the location of the image to load
  97684. */
  97685. function ImageAssetTask(
  97686. /**
  97687. * Defines the name of the task
  97688. */
  97689. name,
  97690. /**
  97691. * Defines the location of the image to load
  97692. */
  97693. url) {
  97694. var _this = _super.call(this, name) || this;
  97695. _this.name = name;
  97696. _this.url = url;
  97697. return _this;
  97698. }
  97699. /**
  97700. * Execute the current task
  97701. * @param scene defines the scene where you want your assets to be loaded
  97702. * @param onSuccess is a callback called when the task is successfully executed
  97703. * @param onError is a callback called if an error occurs
  97704. */
  97705. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97706. var _this = this;
  97707. var img = new Image();
  97708. BABYLON.Tools.SetCorsBehavior(this.url, img);
  97709. img.onload = function () {
  97710. _this.image = img;
  97711. onSuccess();
  97712. };
  97713. img.onerror = function (err) {
  97714. onError("Error loading image", err);
  97715. };
  97716. img.src = this.url;
  97717. };
  97718. return ImageAssetTask;
  97719. }(AbstractAssetTask));
  97720. BABYLON.ImageAssetTask = ImageAssetTask;
  97721. /**
  97722. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  97723. */
  97724. var TextureAssetTask = /** @class */ (function (_super) {
  97725. __extends(TextureAssetTask, _super);
  97726. /**
  97727. * Creates a new TextureAssetTask object
  97728. * @param name defines the name of the task
  97729. * @param url defines the location of the file to load
  97730. * @param noMipmap defines if mipmap should not be generated (default is false)
  97731. * @param invertY defines if texture must be inverted on Y axis (default is false)
  97732. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97733. */
  97734. function TextureAssetTask(
  97735. /**
  97736. * Defines the name of the task
  97737. */
  97738. name,
  97739. /**
  97740. * Defines the location of the file to load
  97741. */
  97742. url,
  97743. /**
  97744. * Defines if mipmap should not be generated (default is false)
  97745. */
  97746. noMipmap,
  97747. /**
  97748. * Defines if texture must be inverted on Y axis (default is false)
  97749. */
  97750. invertY,
  97751. /**
  97752. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97753. */
  97754. samplingMode) {
  97755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97756. var _this = _super.call(this, name) || this;
  97757. _this.name = name;
  97758. _this.url = url;
  97759. _this.noMipmap = noMipmap;
  97760. _this.invertY = invertY;
  97761. _this.samplingMode = samplingMode;
  97762. return _this;
  97763. }
  97764. /**
  97765. * Execute the current task
  97766. * @param scene defines the scene where you want your assets to be loaded
  97767. * @param onSuccess is a callback called when the task is successfully executed
  97768. * @param onError is a callback called if an error occurs
  97769. */
  97770. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97771. var onload = function () {
  97772. onSuccess();
  97773. };
  97774. var onerror = function (message, exception) {
  97775. onError(message, exception);
  97776. };
  97777. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  97778. };
  97779. return TextureAssetTask;
  97780. }(AbstractAssetTask));
  97781. BABYLON.TextureAssetTask = TextureAssetTask;
  97782. /**
  97783. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  97784. */
  97785. var CubeTextureAssetTask = /** @class */ (function (_super) {
  97786. __extends(CubeTextureAssetTask, _super);
  97787. /**
  97788. * Creates a new CubeTextureAssetTask
  97789. * @param name defines the name of the task
  97790. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97791. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97792. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97793. * @param files defines the explicit list of files (undefined by default)
  97794. */
  97795. function CubeTextureAssetTask(
  97796. /**
  97797. * Defines the name of the task
  97798. */
  97799. name,
  97800. /**
  97801. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97802. */
  97803. url,
  97804. /**
  97805. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97806. */
  97807. extensions,
  97808. /**
  97809. * Defines if mipmaps should not be generated (default is false)
  97810. */
  97811. noMipmap,
  97812. /**
  97813. * Defines the explicit list of files (undefined by default)
  97814. */
  97815. files) {
  97816. var _this = _super.call(this, name) || this;
  97817. _this.name = name;
  97818. _this.url = url;
  97819. _this.extensions = extensions;
  97820. _this.noMipmap = noMipmap;
  97821. _this.files = files;
  97822. return _this;
  97823. }
  97824. /**
  97825. * Execute the current task
  97826. * @param scene defines the scene where you want your assets to be loaded
  97827. * @param onSuccess is a callback called when the task is successfully executed
  97828. * @param onError is a callback called if an error occurs
  97829. */
  97830. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97831. var onload = function () {
  97832. onSuccess();
  97833. };
  97834. var onerror = function (message, exception) {
  97835. onError(message, exception);
  97836. };
  97837. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  97838. };
  97839. return CubeTextureAssetTask;
  97840. }(AbstractAssetTask));
  97841. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  97842. /**
  97843. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  97844. */
  97845. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  97846. __extends(HDRCubeTextureAssetTask, _super);
  97847. /**
  97848. * Creates a new HDRCubeTextureAssetTask object
  97849. * @param name defines the name of the task
  97850. * @param url defines the location of the file to load
  97851. * @param size defines the 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.
  97852. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97853. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97854. * @param gammaSpace 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) (default is false)
  97855. * @param reserved Internal use only
  97856. */
  97857. function HDRCubeTextureAssetTask(
  97858. /**
  97859. * Defines the name of the task
  97860. */
  97861. name,
  97862. /**
  97863. * Defines the location of the file to load
  97864. */
  97865. url,
  97866. /**
  97867. * Defines the desired size (the more it increases the longer the generation will be)
  97868. */
  97869. size,
  97870. /**
  97871. * Defines if mipmaps should not be generated (default is false)
  97872. */
  97873. noMipmap,
  97874. /**
  97875. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97876. */
  97877. generateHarmonics,
  97878. /**
  97879. * 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) (default is false)
  97880. */
  97881. gammaSpace,
  97882. /**
  97883. * Internal Use Only
  97884. */
  97885. reserved) {
  97886. if (noMipmap === void 0) { noMipmap = false; }
  97887. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97888. if (gammaSpace === void 0) { gammaSpace = false; }
  97889. if (reserved === void 0) { reserved = false; }
  97890. var _this = _super.call(this, name) || this;
  97891. _this.name = name;
  97892. _this.url = url;
  97893. _this.size = size;
  97894. _this.noMipmap = noMipmap;
  97895. _this.generateHarmonics = generateHarmonics;
  97896. _this.gammaSpace = gammaSpace;
  97897. _this.reserved = reserved;
  97898. return _this;
  97899. }
  97900. /**
  97901. * Execute the current task
  97902. * @param scene defines the scene where you want your assets to be loaded
  97903. * @param onSuccess is a callback called when the task is successfully executed
  97904. * @param onError is a callback called if an error occurs
  97905. */
  97906. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97907. var onload = function () {
  97908. onSuccess();
  97909. };
  97910. var onerror = function (message, exception) {
  97911. onError(message, exception);
  97912. };
  97913. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  97914. };
  97915. return HDRCubeTextureAssetTask;
  97916. }(AbstractAssetTask));
  97917. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  97918. /**
  97919. * This class can be used to easily import assets into a scene
  97920. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  97921. */
  97922. var AssetsManager = /** @class */ (function () {
  97923. /**
  97924. * Creates a new AssetsManager
  97925. * @param scene defines the scene to work on
  97926. */
  97927. function AssetsManager(scene) {
  97928. this._isLoading = false;
  97929. this._tasks = new Array();
  97930. this._waitingTasksCount = 0;
  97931. this._totalTasksCount = 0;
  97932. /**
  97933. * Observable called when all tasks are processed
  97934. */
  97935. this.onTaskSuccessObservable = new BABYLON.Observable();
  97936. /**
  97937. * Observable called when a task had an error
  97938. */
  97939. this.onTaskErrorObservable = new BABYLON.Observable();
  97940. /**
  97941. * Observable called when a task is successful
  97942. */
  97943. this.onTasksDoneObservable = new BABYLON.Observable();
  97944. /**
  97945. * Observable called when a task is done (whatever the result is)
  97946. */
  97947. this.onProgressObservable = new BABYLON.Observable();
  97948. /**
  97949. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  97950. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  97951. */
  97952. this.useDefaultLoadingScreen = true;
  97953. this._scene = scene;
  97954. }
  97955. /**
  97956. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  97957. * @param taskName defines the name of the new task
  97958. * @param meshesNames defines the name of meshes to load
  97959. * @param rootUrl defines the root url to use to locate files
  97960. * @param sceneFilename defines the filename of the scene file
  97961. * @returns a new {BABYLON.MeshAssetTask} object
  97962. */
  97963. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  97964. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  97965. this._tasks.push(task);
  97966. return task;
  97967. };
  97968. /**
  97969. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  97970. * @param taskName defines the name of the new task
  97971. * @param url defines the url of the file to load
  97972. * @returns a new {BABYLON.TextFileAssetTask} object
  97973. */
  97974. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  97975. var task = new TextFileAssetTask(taskName, url);
  97976. this._tasks.push(task);
  97977. return task;
  97978. };
  97979. /**
  97980. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  97981. * @param taskName defines the name of the new task
  97982. * @param url defines the url of the file to load
  97983. * @returns a new {BABYLON.BinaryFileAssetTask} object
  97984. */
  97985. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  97986. var task = new BinaryFileAssetTask(taskName, url);
  97987. this._tasks.push(task);
  97988. return task;
  97989. };
  97990. /**
  97991. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  97992. * @param taskName defines the name of the new task
  97993. * @param url defines the url of the file to load
  97994. * @returns a new {BABYLON.ImageAssetTask} object
  97995. */
  97996. AssetsManager.prototype.addImageTask = function (taskName, url) {
  97997. var task = new ImageAssetTask(taskName, url);
  97998. this._tasks.push(task);
  97999. return task;
  98000. };
  98001. /**
  98002. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98003. * @param taskName defines the name of the new task
  98004. * @param url defines the url of the file to load
  98005. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98006. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98007. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98008. * @returns a new {BABYLON.TextureAssetTask} object
  98009. */
  98010. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98011. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98012. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98013. this._tasks.push(task);
  98014. return task;
  98015. };
  98016. /**
  98017. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98018. * @param taskName defines the name of the new task
  98019. * @param url defines the url of the file to load
  98020. * @param extensions defines the extension to use to load the cube map (can be null)
  98021. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98022. * @param files defines the list of files to load (can be null)
  98023. * @returns a new {BABYLON.CubeTextureAssetTask} object
  98024. */
  98025. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  98026. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  98027. this._tasks.push(task);
  98028. return task;
  98029. };
  98030. /**
  98031. *
  98032. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  98033. * @param taskName defines the name of the new task
  98034. * @param url defines the url of the file to load
  98035. * @param size defines the size you want for the cubemap (can be null)
  98036. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98037. * @param generateHarmonics defines if you want to automatically generate (true by default)
  98038. * @param gammaSpace 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) (default is false)
  98039. * @param reserved Internal use only
  98040. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  98041. */
  98042. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  98043. if (noMipmap === void 0) { noMipmap = false; }
  98044. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98045. if (gammaSpace === void 0) { gammaSpace = false; }
  98046. if (reserved === void 0) { reserved = false; }
  98047. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  98048. this._tasks.push(task);
  98049. return task;
  98050. };
  98051. /**
  98052. * Remove a task from the assets manager.
  98053. * @param task the task to remove
  98054. */
  98055. AssetsManager.prototype.removeTask = function (task) {
  98056. var index = this._tasks.indexOf(task);
  98057. if (index > -1) {
  98058. this._tasks.splice(index, 1);
  98059. }
  98060. };
  98061. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  98062. this._waitingTasksCount--;
  98063. try {
  98064. if (this.onProgress) {
  98065. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  98066. }
  98067. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  98068. }
  98069. catch (e) {
  98070. BABYLON.Tools.Error("Error running progress callbacks.");
  98071. console.log(e);
  98072. }
  98073. if (this._waitingTasksCount === 0) {
  98074. try {
  98075. if (this.onFinish) {
  98076. this.onFinish(this._tasks);
  98077. }
  98078. // Let's remove successfull tasks
  98079. var currentTasks = this._tasks.slice();
  98080. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  98081. var task = currentTasks_1[_i];
  98082. if (task.taskState === AssetTaskState.DONE) {
  98083. var index = this._tasks.indexOf(task);
  98084. if (index > -1) {
  98085. this._tasks.splice(index, 1);
  98086. }
  98087. }
  98088. }
  98089. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98090. }
  98091. catch (e) {
  98092. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  98093. console.log(e);
  98094. }
  98095. this._isLoading = false;
  98096. this._scene.getEngine().hideLoadingUI();
  98097. }
  98098. };
  98099. AssetsManager.prototype._runTask = function (task) {
  98100. var _this = this;
  98101. var done = function () {
  98102. try {
  98103. if (_this.onTaskSuccess) {
  98104. _this.onTaskSuccess(task);
  98105. }
  98106. _this.onTaskSuccessObservable.notifyObservers(task);
  98107. _this._decreaseWaitingTasksCount(task);
  98108. }
  98109. catch (e) {
  98110. error("Error executing task success callbacks", e);
  98111. }
  98112. };
  98113. var error = function (message, exception) {
  98114. task._setErrorObject(message, exception);
  98115. if (_this.onTaskError) {
  98116. _this.onTaskError(task);
  98117. }
  98118. _this.onTaskErrorObservable.notifyObservers(task);
  98119. _this._decreaseWaitingTasksCount(task);
  98120. };
  98121. task.run(this._scene, done, error);
  98122. };
  98123. /**
  98124. * Reset the {BABYLON.AssetsManager} and remove all tasks
  98125. * @return the current instance of the {BABYLON.AssetsManager}
  98126. */
  98127. AssetsManager.prototype.reset = function () {
  98128. this._isLoading = false;
  98129. this._tasks = new Array();
  98130. return this;
  98131. };
  98132. /**
  98133. * Start the loading process
  98134. * @return the current instance of the {BABYLON.AssetsManager}
  98135. */
  98136. AssetsManager.prototype.load = function () {
  98137. if (this._isLoading) {
  98138. return this;
  98139. }
  98140. this._isLoading = true;
  98141. this._waitingTasksCount = this._tasks.length;
  98142. this._totalTasksCount = this._tasks.length;
  98143. if (this._waitingTasksCount === 0) {
  98144. this._isLoading = false;
  98145. if (this.onFinish) {
  98146. this.onFinish(this._tasks);
  98147. }
  98148. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98149. return this;
  98150. }
  98151. if (this.useDefaultLoadingScreen) {
  98152. this._scene.getEngine().displayLoadingUI();
  98153. }
  98154. for (var index = 0; index < this._tasks.length; index++) {
  98155. var task = this._tasks[index];
  98156. if (task.taskState === AssetTaskState.INIT) {
  98157. this._runTask(task);
  98158. }
  98159. }
  98160. return this;
  98161. };
  98162. return AssetsManager;
  98163. }());
  98164. BABYLON.AssetsManager = AssetsManager;
  98165. })(BABYLON || (BABYLON = {}));
  98166. //# sourceMappingURL=babylon.assetsManager.js.map
  98167. var BABYLON;
  98168. (function (BABYLON) {
  98169. var serializedGeometries = [];
  98170. var serializeGeometry = function (geometry, serializationGeometries) {
  98171. if (serializedGeometries[geometry.id]) {
  98172. return;
  98173. }
  98174. if (geometry.doNotSerialize) {
  98175. return;
  98176. }
  98177. if (geometry instanceof BABYLON.BoxGeometry) {
  98178. serializationGeometries.boxes.push(geometry.serialize());
  98179. }
  98180. else if (geometry instanceof BABYLON.SphereGeometry) {
  98181. serializationGeometries.spheres.push(geometry.serialize());
  98182. }
  98183. else if (geometry instanceof BABYLON.CylinderGeometry) {
  98184. serializationGeometries.cylinders.push(geometry.serialize());
  98185. }
  98186. else if (geometry instanceof BABYLON.TorusGeometry) {
  98187. serializationGeometries.toruses.push(geometry.serialize());
  98188. }
  98189. else if (geometry instanceof BABYLON.GroundGeometry) {
  98190. serializationGeometries.grounds.push(geometry.serialize());
  98191. }
  98192. else if (geometry instanceof BABYLON.Plane) {
  98193. serializationGeometries.planes.push(geometry.serialize());
  98194. }
  98195. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  98196. serializationGeometries.torusKnots.push(geometry.serialize());
  98197. }
  98198. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  98199. throw new Error("Unknown primitive type");
  98200. }
  98201. else {
  98202. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  98203. }
  98204. serializedGeometries[geometry.id] = true;
  98205. };
  98206. var serializeMesh = function (mesh, serializationScene) {
  98207. var serializationObject = {};
  98208. // Geometry
  98209. var geometry = mesh._geometry;
  98210. if (geometry) {
  98211. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  98212. // 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
  98213. serializeGeometry(geometry, serializationScene.geometries);
  98214. }
  98215. }
  98216. // Custom
  98217. if (mesh.serialize) {
  98218. mesh.serialize(serializationObject);
  98219. }
  98220. return serializationObject;
  98221. };
  98222. var finalizeSingleMesh = function (mesh, serializationObject) {
  98223. //only works if the mesh is already loaded
  98224. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98225. //serialize material
  98226. if (mesh.material) {
  98227. if (mesh.material instanceof BABYLON.MultiMaterial) {
  98228. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  98229. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98230. serializationObject.multiMaterials.push(mesh.material.serialize());
  98231. }
  98232. }
  98233. else {
  98234. serializationObject.materials = serializationObject.materials || [];
  98235. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98236. serializationObject.materials.push(mesh.material.serialize());
  98237. }
  98238. }
  98239. }
  98240. //serialize geometry
  98241. var geometry = mesh._geometry;
  98242. if (geometry) {
  98243. if (!serializationObject.geometries) {
  98244. serializationObject.geometries = {};
  98245. serializationObject.geometries.boxes = [];
  98246. serializationObject.geometries.spheres = [];
  98247. serializationObject.geometries.cylinders = [];
  98248. serializationObject.geometries.toruses = [];
  98249. serializationObject.geometries.grounds = [];
  98250. serializationObject.geometries.planes = [];
  98251. serializationObject.geometries.torusKnots = [];
  98252. serializationObject.geometries.vertexData = [];
  98253. }
  98254. serializeGeometry(geometry, serializationObject.geometries);
  98255. }
  98256. // Skeletons
  98257. if (mesh.skeleton) {
  98258. serializationObject.skeletons = serializationObject.skeletons || [];
  98259. serializationObject.skeletons.push(mesh.skeleton.serialize());
  98260. }
  98261. //serialize the actual mesh
  98262. serializationObject.meshes = serializationObject.meshes || [];
  98263. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98264. }
  98265. };
  98266. var SceneSerializer = /** @class */ (function () {
  98267. function SceneSerializer() {
  98268. }
  98269. SceneSerializer.ClearCache = function () {
  98270. serializedGeometries = [];
  98271. };
  98272. SceneSerializer.Serialize = function (scene) {
  98273. var serializationObject = {};
  98274. SceneSerializer.ClearCache();
  98275. // Scene
  98276. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  98277. serializationObject.autoClear = scene.autoClear;
  98278. serializationObject.clearColor = scene.clearColor.asArray();
  98279. serializationObject.ambientColor = scene.ambientColor.asArray();
  98280. serializationObject.gravity = scene.gravity.asArray();
  98281. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  98282. serializationObject.workerCollisions = scene.workerCollisions;
  98283. // Fog
  98284. if (scene.fogMode && scene.fogMode !== 0) {
  98285. serializationObject.fogMode = scene.fogMode;
  98286. serializationObject.fogColor = scene.fogColor.asArray();
  98287. serializationObject.fogStart = scene.fogStart;
  98288. serializationObject.fogEnd = scene.fogEnd;
  98289. serializationObject.fogDensity = scene.fogDensity;
  98290. }
  98291. //Physics
  98292. if (scene.isPhysicsEnabled()) {
  98293. var physicEngine = scene.getPhysicsEngine();
  98294. if (physicEngine) {
  98295. serializationObject.physicsEnabled = true;
  98296. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  98297. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  98298. }
  98299. }
  98300. // Metadata
  98301. if (scene.metadata) {
  98302. serializationObject.metadata = scene.metadata;
  98303. }
  98304. // Morph targets
  98305. serializationObject.morphTargetManagers = [];
  98306. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  98307. var abstractMesh = _a[_i];
  98308. var manager = abstractMesh.morphTargetManager;
  98309. if (manager) {
  98310. serializationObject.morphTargetManagers.push(manager.serialize());
  98311. }
  98312. }
  98313. // Lights
  98314. serializationObject.lights = [];
  98315. var index;
  98316. var light;
  98317. for (index = 0; index < scene.lights.length; index++) {
  98318. light = scene.lights[index];
  98319. if (!light.doNotSerialize) {
  98320. serializationObject.lights.push(light.serialize());
  98321. }
  98322. }
  98323. // Cameras
  98324. serializationObject.cameras = [];
  98325. for (index = 0; index < scene.cameras.length; index++) {
  98326. var camera = scene.cameras[index];
  98327. if (!camera.doNotSerialize) {
  98328. serializationObject.cameras.push(camera.serialize());
  98329. }
  98330. }
  98331. if (scene.activeCamera) {
  98332. serializationObject.activeCameraID = scene.activeCamera.id;
  98333. }
  98334. // Animations
  98335. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  98336. // Materials
  98337. serializationObject.materials = [];
  98338. serializationObject.multiMaterials = [];
  98339. var material;
  98340. for (index = 0; index < scene.materials.length; index++) {
  98341. material = scene.materials[index];
  98342. if (!material.doNotSerialize) {
  98343. serializationObject.materials.push(material.serialize());
  98344. }
  98345. }
  98346. // MultiMaterials
  98347. serializationObject.multiMaterials = [];
  98348. for (index = 0; index < scene.multiMaterials.length; index++) {
  98349. var multiMaterial = scene.multiMaterials[index];
  98350. serializationObject.multiMaterials.push(multiMaterial.serialize());
  98351. }
  98352. // Environment texture
  98353. if (scene.environmentTexture) {
  98354. serializationObject.environmentTexture = scene.environmentTexture.name;
  98355. }
  98356. // Skeletons
  98357. serializationObject.skeletons = [];
  98358. for (index = 0; index < scene.skeletons.length; index++) {
  98359. var skeleton = scene.skeletons[index];
  98360. if (!skeleton.doNotSerialize) {
  98361. serializationObject.skeletons.push(skeleton.serialize());
  98362. }
  98363. }
  98364. // Transform nodes
  98365. serializationObject.transformNodes = [];
  98366. for (index = 0; index < scene.transformNodes.length; index++) {
  98367. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  98368. }
  98369. // Geometries
  98370. serializationObject.geometries = {};
  98371. serializationObject.geometries.boxes = [];
  98372. serializationObject.geometries.spheres = [];
  98373. serializationObject.geometries.cylinders = [];
  98374. serializationObject.geometries.toruses = [];
  98375. serializationObject.geometries.grounds = [];
  98376. serializationObject.geometries.planes = [];
  98377. serializationObject.geometries.torusKnots = [];
  98378. serializationObject.geometries.vertexData = [];
  98379. serializedGeometries = [];
  98380. var geometries = scene.getGeometries();
  98381. for (index = 0; index < geometries.length; index++) {
  98382. var geometry = geometries[index];
  98383. if (geometry.isReady()) {
  98384. serializeGeometry(geometry, serializationObject.geometries);
  98385. }
  98386. }
  98387. // Meshes
  98388. serializationObject.meshes = [];
  98389. for (index = 0; index < scene.meshes.length; index++) {
  98390. var abstractMesh = scene.meshes[index];
  98391. if (abstractMesh instanceof BABYLON.Mesh) {
  98392. var mesh = abstractMesh;
  98393. if (!mesh.doNotSerialize) {
  98394. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98395. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98396. }
  98397. }
  98398. }
  98399. }
  98400. // Particles Systems
  98401. serializationObject.particleSystems = [];
  98402. for (index = 0; index < scene.particleSystems.length; index++) {
  98403. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  98404. }
  98405. // Shadows
  98406. serializationObject.shadowGenerators = [];
  98407. for (index = 0; index < scene.lights.length; index++) {
  98408. light = scene.lights[index];
  98409. var shadowGenerator = light.getShadowGenerator();
  98410. if (shadowGenerator) {
  98411. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  98412. }
  98413. }
  98414. // Action Manager
  98415. if (scene.actionManager) {
  98416. serializationObject.actions = scene.actionManager.serialize("scene");
  98417. }
  98418. // Audio
  98419. serializationObject.sounds = [];
  98420. for (index = 0; index < scene.soundTracks.length; index++) {
  98421. var soundtrack = scene.soundTracks[index];
  98422. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  98423. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  98424. }
  98425. }
  98426. // Components
  98427. for (var _b = 0, _c = scene._components; _b < _c.length; _b++) {
  98428. var component = _c[_b];
  98429. component.serialize(serializationObject);
  98430. }
  98431. return serializationObject;
  98432. };
  98433. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  98434. if (withParents === void 0) { withParents = false; }
  98435. if (withChildren === void 0) { withChildren = false; }
  98436. var serializationObject = {};
  98437. SceneSerializer.ClearCache();
  98438. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  98439. if (withParents || withChildren) {
  98440. //deliberate for loop! not for each, appended should be processed as well.
  98441. for (var i = 0; i < toSerialize.length; ++i) {
  98442. if (withChildren) {
  98443. toSerialize[i].getDescendants().forEach(function (node) {
  98444. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  98445. toSerialize.push(node);
  98446. }
  98447. });
  98448. }
  98449. //make sure the array doesn't contain the object already
  98450. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  98451. toSerialize.push(toSerialize[i].parent);
  98452. }
  98453. }
  98454. }
  98455. toSerialize.forEach(function (mesh) {
  98456. finalizeSingleMesh(mesh, serializationObject);
  98457. });
  98458. return serializationObject;
  98459. };
  98460. return SceneSerializer;
  98461. }());
  98462. BABYLON.SceneSerializer = SceneSerializer;
  98463. })(BABYLON || (BABYLON = {}));
  98464. //# sourceMappingURL=babylon.sceneSerializer.js.map
  98465. var BABYLON;
  98466. (function (BABYLON) {
  98467. var ReflectionProbe = /** @class */ (function () {
  98468. function ReflectionProbe(name, size, scene, generateMipMaps) {
  98469. if (generateMipMaps === void 0) { generateMipMaps = true; }
  98470. var _this = this;
  98471. this.name = name;
  98472. this._viewMatrix = BABYLON.Matrix.Identity();
  98473. this._target = BABYLON.Vector3.Zero();
  98474. this._add = BABYLON.Vector3.Zero();
  98475. this._invertYAxis = false;
  98476. this.position = BABYLON.Vector3.Zero();
  98477. this._scene = scene;
  98478. this._scene.reflectionProbes.push(this);
  98479. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  98480. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  98481. switch (faceIndex) {
  98482. case 0:
  98483. _this._add.copyFromFloats(1, 0, 0);
  98484. break;
  98485. case 1:
  98486. _this._add.copyFromFloats(-1, 0, 0);
  98487. break;
  98488. case 2:
  98489. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  98490. break;
  98491. case 3:
  98492. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  98493. break;
  98494. case 4:
  98495. _this._add.copyFromFloats(0, 0, 1);
  98496. break;
  98497. case 5:
  98498. _this._add.copyFromFloats(0, 0, -1);
  98499. break;
  98500. }
  98501. if (_this._attachedMesh) {
  98502. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  98503. }
  98504. _this.position.addToRef(_this._add, _this._target);
  98505. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  98506. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  98507. scene._forcedViewPosition = _this.position;
  98508. });
  98509. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  98510. scene._forcedViewPosition = null;
  98511. scene.updateTransformMatrix(true);
  98512. });
  98513. if (scene.activeCamera) {
  98514. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  98515. }
  98516. }
  98517. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  98518. get: function () {
  98519. return this._renderTargetTexture.samples;
  98520. },
  98521. set: function (value) {
  98522. this._renderTargetTexture.samples = value;
  98523. },
  98524. enumerable: true,
  98525. configurable: true
  98526. });
  98527. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  98528. get: function () {
  98529. return this._renderTargetTexture.refreshRate;
  98530. },
  98531. set: function (value) {
  98532. this._renderTargetTexture.refreshRate = value;
  98533. },
  98534. enumerable: true,
  98535. configurable: true
  98536. });
  98537. ReflectionProbe.prototype.getScene = function () {
  98538. return this._scene;
  98539. };
  98540. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  98541. get: function () {
  98542. return this._renderTargetTexture;
  98543. },
  98544. enumerable: true,
  98545. configurable: true
  98546. });
  98547. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  98548. get: function () {
  98549. return this._renderTargetTexture.renderList;
  98550. },
  98551. enumerable: true,
  98552. configurable: true
  98553. });
  98554. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  98555. this._attachedMesh = mesh;
  98556. };
  98557. /**
  98558. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  98559. *
  98560. * @param renderingGroupId The rendering group id corresponding to its index
  98561. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  98562. */
  98563. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  98564. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  98565. };
  98566. ReflectionProbe.prototype.dispose = function () {
  98567. var index = this._scene.reflectionProbes.indexOf(this);
  98568. if (index !== -1) {
  98569. // Remove from the scene if found
  98570. this._scene.reflectionProbes.splice(index, 1);
  98571. }
  98572. if (this._renderTargetTexture) {
  98573. this._renderTargetTexture.dispose();
  98574. this._renderTargetTexture = null;
  98575. }
  98576. };
  98577. return ReflectionProbe;
  98578. }());
  98579. BABYLON.ReflectionProbe = ReflectionProbe;
  98580. })(BABYLON || (BABYLON = {}));
  98581. //# sourceMappingURL=babylon.reflectionProbe.js.map
  98582. var BABYLON;
  98583. (function (BABYLON) {
  98584. /**
  98585. * Defines the layer scene component responsible to manage any layers
  98586. * in a given scene.
  98587. */
  98588. var LayerSceneComponent = /** @class */ (function () {
  98589. /**
  98590. * Creates a new instance of the component for the given scene
  98591. * @param scene Defines the scene to register the component in
  98592. */
  98593. function LayerSceneComponent(scene) {
  98594. /**
  98595. * The component name helpfull to identify the component in the list of scene components.
  98596. */
  98597. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  98598. this.scene = scene;
  98599. this._engine = scene.getEngine();
  98600. this._layers = scene.layers = new Array();
  98601. }
  98602. /**
  98603. * Registers the component in a given scene
  98604. */
  98605. LayerSceneComponent.prototype.register = function () {
  98606. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  98607. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  98608. };
  98609. /**
  98610. * Rebuilds the elements related to this component in case of
  98611. * context lost for instance.
  98612. */
  98613. LayerSceneComponent.prototype.rebuild = function () {
  98614. for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
  98615. var layer = _a[_i];
  98616. layer._rebuild();
  98617. }
  98618. };
  98619. /**
  98620. * Serializes the component data to the specified json object
  98621. * @param serializationObject The object to serialize to
  98622. */
  98623. LayerSceneComponent.prototype.serialize = function (serializationObject) {
  98624. // TODO. Implement layer serialization
  98625. // serializationObject.layers = [];
  98626. // for (let layer of this._layers) {
  98627. // if (layer.serialize) {
  98628. // serializationObject.layers.push(layer.serialize());
  98629. // }
  98630. // }
  98631. };
  98632. /**
  98633. * Adds all the element from the container to the scene
  98634. * @param container the container holding the elements
  98635. */
  98636. LayerSceneComponent.prototype.addFromContainer = function (container) {
  98637. if (!container.layers) {
  98638. return;
  98639. }
  98640. // container.layers.forEach((o) => {
  98641. // this.scene.addLayer(o);
  98642. // });
  98643. };
  98644. /**
  98645. * Removes all the elements in the container from the scene
  98646. * @param container contains the elements to remove
  98647. */
  98648. LayerSceneComponent.prototype.removeFromContainer = function (container) {
  98649. if (!container.layers) {
  98650. return;
  98651. }
  98652. // container.layers.forEach((o) => {
  98653. // this.scene.removeLayer(o);
  98654. // });
  98655. };
  98656. /**
  98657. * Disposes the component and the associated ressources.
  98658. */
  98659. LayerSceneComponent.prototype.dispose = function () {
  98660. while (this._layers.length) {
  98661. this._layers[0].dispose();
  98662. }
  98663. };
  98664. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  98665. if (this._layers.length) {
  98666. this._engine.setDepthBuffer(false);
  98667. var cameraLayerMask = camera.layerMask;
  98668. for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
  98669. var layer = _a[_i];
  98670. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  98671. layer.render();
  98672. }
  98673. }
  98674. this._engine.setDepthBuffer(true);
  98675. }
  98676. };
  98677. LayerSceneComponent.prototype._drawBackground = function (camera) {
  98678. this._draw(camera, true);
  98679. };
  98680. LayerSceneComponent.prototype._drawForeground = function (camera) {
  98681. this._draw(camera, false);
  98682. };
  98683. return LayerSceneComponent;
  98684. }());
  98685. BABYLON.LayerSceneComponent = LayerSceneComponent;
  98686. })(BABYLON || (BABYLON = {}));
  98687. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  98688. var BABYLON;
  98689. (function (BABYLON) {
  98690. var Layer = /** @class */ (function () {
  98691. function Layer(name, imgUrl, scene, isBackground, color) {
  98692. this.name = name;
  98693. this.scale = new BABYLON.Vector2(1, 1);
  98694. this.offset = new BABYLON.Vector2(0, 0);
  98695. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  98696. this.layerMask = 0x0FFFFFFF;
  98697. this._vertexBuffers = {};
  98698. // Events
  98699. /**
  98700. * An event triggered when the layer is disposed.
  98701. */
  98702. this.onDisposeObservable = new BABYLON.Observable();
  98703. /**
  98704. * An event triggered before rendering the scene
  98705. */
  98706. this.onBeforeRenderObservable = new BABYLON.Observable();
  98707. /**
  98708. * An event triggered after rendering the scene
  98709. */
  98710. this.onAfterRenderObservable = new BABYLON.Observable();
  98711. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  98712. this.isBackground = isBackground === undefined ? true : isBackground;
  98713. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  98714. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  98715. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  98716. if (!layerComponent) {
  98717. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  98718. this._scene._addComponent(layerComponent);
  98719. }
  98720. this._scene.layers.push(this);
  98721. var engine = this._scene.getEngine();
  98722. // VBO
  98723. var vertices = [];
  98724. vertices.push(1, 1);
  98725. vertices.push(-1, 1);
  98726. vertices.push(-1, -1);
  98727. vertices.push(1, -1);
  98728. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  98729. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  98730. this._createIndexBuffer();
  98731. // Effects
  98732. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  98733. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  98734. }
  98735. Object.defineProperty(Layer.prototype, "onDispose", {
  98736. set: function (callback) {
  98737. if (this._onDisposeObserver) {
  98738. this.onDisposeObservable.remove(this._onDisposeObserver);
  98739. }
  98740. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  98741. },
  98742. enumerable: true,
  98743. configurable: true
  98744. });
  98745. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  98746. set: function (callback) {
  98747. if (this._onBeforeRenderObserver) {
  98748. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  98749. }
  98750. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  98751. },
  98752. enumerable: true,
  98753. configurable: true
  98754. });
  98755. Object.defineProperty(Layer.prototype, "onAfterRender", {
  98756. set: function (callback) {
  98757. if (this._onAfterRenderObserver) {
  98758. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98759. }
  98760. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  98761. },
  98762. enumerable: true,
  98763. configurable: true
  98764. });
  98765. Layer.prototype._createIndexBuffer = function () {
  98766. var engine = this._scene.getEngine();
  98767. // Indices
  98768. var indices = [];
  98769. indices.push(0);
  98770. indices.push(1);
  98771. indices.push(2);
  98772. indices.push(0);
  98773. indices.push(2);
  98774. indices.push(3);
  98775. this._indexBuffer = engine.createIndexBuffer(indices);
  98776. };
  98777. Layer.prototype._rebuild = function () {
  98778. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98779. if (vb) {
  98780. vb._rebuild();
  98781. }
  98782. this._createIndexBuffer();
  98783. };
  98784. Layer.prototype.render = function () {
  98785. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  98786. // Check
  98787. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  98788. return;
  98789. var engine = this._scene.getEngine();
  98790. this.onBeforeRenderObservable.notifyObservers(this);
  98791. // Render
  98792. engine.enableEffect(currentEffect);
  98793. engine.setState(false);
  98794. // Texture
  98795. currentEffect.setTexture("textureSampler", this.texture);
  98796. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  98797. // Color
  98798. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  98799. // Scale / offset
  98800. currentEffect.setVector2("offset", this.offset);
  98801. currentEffect.setVector2("scale", this.scale);
  98802. // VBOs
  98803. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  98804. // Draw order
  98805. if (!this.alphaTest) {
  98806. engine.setAlphaMode(this.alphaBlendingMode);
  98807. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98808. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  98809. }
  98810. else {
  98811. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98812. }
  98813. this.onAfterRenderObservable.notifyObservers(this);
  98814. };
  98815. Layer.prototype.dispose = function () {
  98816. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98817. if (vertexBuffer) {
  98818. vertexBuffer.dispose();
  98819. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  98820. }
  98821. if (this._indexBuffer) {
  98822. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  98823. this._indexBuffer = null;
  98824. }
  98825. if (this.texture) {
  98826. this.texture.dispose();
  98827. this.texture = null;
  98828. }
  98829. // Remove from scene
  98830. var index = this._scene.layers.indexOf(this);
  98831. this._scene.layers.splice(index, 1);
  98832. // Callback
  98833. this.onDisposeObservable.notifyObservers(this);
  98834. this.onDisposeObservable.clear();
  98835. this.onAfterRenderObservable.clear();
  98836. this.onBeforeRenderObservable.clear();
  98837. };
  98838. return Layer;
  98839. }());
  98840. BABYLON.Layer = Layer;
  98841. })(BABYLON || (BABYLON = {}));
  98842. //# sourceMappingURL=babylon.layer.js.map
  98843. var BABYLON;
  98844. (function (BABYLON) {
  98845. var TextureTools = /** @class */ (function () {
  98846. function TextureTools() {
  98847. }
  98848. /**
  98849. * Uses the GPU to create a copy texture rescaled at a given size
  98850. * @param texture Texture to copy from
  98851. * @param width Desired width
  98852. * @param height Desired height
  98853. * @return Generated texture
  98854. */
  98855. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  98856. if (useBilinearMode === void 0) { useBilinearMode = true; }
  98857. var scene = texture.getScene();
  98858. var engine = scene.getEngine();
  98859. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  98860. rtt.wrapU = texture.wrapU;
  98861. rtt.wrapV = texture.wrapV;
  98862. rtt.uOffset = texture.uOffset;
  98863. rtt.vOffset = texture.vOffset;
  98864. rtt.uScale = texture.uScale;
  98865. rtt.vScale = texture.vScale;
  98866. rtt.uAng = texture.uAng;
  98867. rtt.vAng = texture.vAng;
  98868. rtt.wAng = texture.wAng;
  98869. rtt.coordinatesIndex = texture.coordinatesIndex;
  98870. rtt.level = texture.level;
  98871. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  98872. rtt._texture.isReady = false;
  98873. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98874. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98875. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  98876. passPostProcess.getEffect().executeWhenCompiled(function () {
  98877. passPostProcess.onApply = function (effect) {
  98878. effect.setTexture("textureSampler", texture);
  98879. };
  98880. var internalTexture = rtt.getInternalTexture();
  98881. if (internalTexture) {
  98882. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  98883. engine.unBindFramebuffer(internalTexture);
  98884. rtt.disposeFramebufferObjects();
  98885. passPostProcess.dispose();
  98886. internalTexture.isReady = true;
  98887. }
  98888. });
  98889. return rtt;
  98890. };
  98891. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  98892. if (!scene._environmentBRDFTexture) {
  98893. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98894. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98895. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98896. scene._environmentBRDFTexture = texture;
  98897. }
  98898. return scene._environmentBRDFTexture;
  98899. };
  98900. 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=";
  98901. return TextureTools;
  98902. }());
  98903. BABYLON.TextureTools = TextureTools;
  98904. })(BABYLON || (BABYLON = {}));
  98905. //# sourceMappingURL=babylon.textureTools.js.map
  98906. var BABYLON;
  98907. (function (BABYLON) {
  98908. var FramingBehavior = /** @class */ (function () {
  98909. function FramingBehavior() {
  98910. this._mode = FramingBehavior.FitFrustumSidesMode;
  98911. this._radiusScale = 1.0;
  98912. this._positionScale = 0.5;
  98913. this._defaultElevation = 0.3;
  98914. this._elevationReturnTime = 1500;
  98915. this._elevationReturnWaitTime = 1000;
  98916. this._zoomStopsAnimation = false;
  98917. this._framingTime = 1500;
  98918. this._isPointerDown = false;
  98919. this._lastInteractionTime = -Infinity;
  98920. // Framing control
  98921. this._animatables = new Array();
  98922. this._betaIsAnimating = false;
  98923. }
  98924. Object.defineProperty(FramingBehavior.prototype, "name", {
  98925. get: function () {
  98926. return "Framing";
  98927. },
  98928. enumerable: true,
  98929. configurable: true
  98930. });
  98931. Object.defineProperty(FramingBehavior.prototype, "mode", {
  98932. /**
  98933. * Gets current mode used by the behavior.
  98934. */
  98935. get: function () {
  98936. return this._mode;
  98937. },
  98938. /**
  98939. * Sets the current mode used by the behavior
  98940. */
  98941. set: function (mode) {
  98942. this._mode = mode;
  98943. },
  98944. enumerable: true,
  98945. configurable: true
  98946. });
  98947. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  98948. /**
  98949. * Gets the scale applied to the radius
  98950. */
  98951. get: function () {
  98952. return this._radiusScale;
  98953. },
  98954. /**
  98955. * Sets the scale applied to the radius (1 by default)
  98956. */
  98957. set: function (radius) {
  98958. this._radiusScale = radius;
  98959. },
  98960. enumerable: true,
  98961. configurable: true
  98962. });
  98963. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  98964. /**
  98965. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98966. */
  98967. get: function () {
  98968. return this._positionScale;
  98969. },
  98970. /**
  98971. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98972. */
  98973. set: function (scale) {
  98974. this._positionScale = scale;
  98975. },
  98976. enumerable: true,
  98977. configurable: true
  98978. });
  98979. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  98980. /**
  98981. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98982. * behaviour is triggered, in radians.
  98983. */
  98984. get: function () {
  98985. return this._defaultElevation;
  98986. },
  98987. /**
  98988. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98989. * behaviour is triggered, in radians.
  98990. */
  98991. set: function (elevation) {
  98992. this._defaultElevation = elevation;
  98993. },
  98994. enumerable: true,
  98995. configurable: true
  98996. });
  98997. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  98998. /**
  98999. * Gets the time (in milliseconds) taken to return to the default beta position.
  99000. * Negative value indicates camera should not return to default.
  99001. */
  99002. get: function () {
  99003. return this._elevationReturnTime;
  99004. },
  99005. /**
  99006. * Sets the time (in milliseconds) taken to return to the default beta position.
  99007. * Negative value indicates camera should not return to default.
  99008. */
  99009. set: function (speed) {
  99010. this._elevationReturnTime = speed;
  99011. },
  99012. enumerable: true,
  99013. configurable: true
  99014. });
  99015. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99016. /**
  99017. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99018. */
  99019. get: function () {
  99020. return this._elevationReturnWaitTime;
  99021. },
  99022. /**
  99023. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99024. */
  99025. set: function (time) {
  99026. this._elevationReturnWaitTime = time;
  99027. },
  99028. enumerable: true,
  99029. configurable: true
  99030. });
  99031. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99032. /**
  99033. * Gets the flag that indicates if user zooming should stop animation.
  99034. */
  99035. get: function () {
  99036. return this._zoomStopsAnimation;
  99037. },
  99038. /**
  99039. * Sets the flag that indicates if user zooming should stop animation.
  99040. */
  99041. set: function (flag) {
  99042. this._zoomStopsAnimation = flag;
  99043. },
  99044. enumerable: true,
  99045. configurable: true
  99046. });
  99047. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99048. /**
  99049. * Gets the transition time when framing the mesh, in milliseconds
  99050. */
  99051. get: function () {
  99052. return this._framingTime;
  99053. },
  99054. /**
  99055. * Sets the transition time when framing the mesh, in milliseconds
  99056. */
  99057. set: function (time) {
  99058. this._framingTime = time;
  99059. },
  99060. enumerable: true,
  99061. configurable: true
  99062. });
  99063. FramingBehavior.prototype.init = function () {
  99064. // Do notihng
  99065. };
  99066. FramingBehavior.prototype.attach = function (camera) {
  99067. var _this = this;
  99068. this._attachedCamera = camera;
  99069. var scene = this._attachedCamera.getScene();
  99070. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  99071. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99072. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99073. _this._isPointerDown = true;
  99074. return;
  99075. }
  99076. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99077. _this._isPointerDown = false;
  99078. }
  99079. });
  99080. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99081. if (mesh) {
  99082. _this.zoomOnMesh(mesh);
  99083. }
  99084. });
  99085. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99086. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99087. _this._applyUserInteraction();
  99088. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  99089. // back to the default position after a given timeout
  99090. _this._maintainCameraAboveGround();
  99091. });
  99092. };
  99093. FramingBehavior.prototype.detach = function () {
  99094. if (!this._attachedCamera) {
  99095. return;
  99096. }
  99097. var scene = this._attachedCamera.getScene();
  99098. if (this._onPrePointerObservableObserver) {
  99099. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99100. }
  99101. if (this._onAfterCheckInputsObserver) {
  99102. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99103. }
  99104. if (this._onMeshTargetChangedObserver) {
  99105. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99106. }
  99107. this._attachedCamera = null;
  99108. };
  99109. /**
  99110. * Targets the given mesh and updates zoom level accordingly.
  99111. * @param mesh The mesh to target.
  99112. * @param radius Optional. If a cached radius position already exists, overrides default.
  99113. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99114. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99115. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99116. */
  99117. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99118. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99119. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99120. mesh.computeWorldMatrix(true);
  99121. var boundingBox = mesh.getBoundingInfo().boundingBox;
  99122. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  99123. };
  99124. /**
  99125. * Targets the given mesh with its children and updates zoom level accordingly.
  99126. * @param mesh The mesh to target.
  99127. * @param radius Optional. If a cached radius position already exists, overrides default.
  99128. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99129. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99130. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99131. */
  99132. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99133. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99134. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99135. mesh.computeWorldMatrix(true);
  99136. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  99137. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  99138. };
  99139. /**
  99140. * Targets the given meshes with their children and updates zoom level accordingly.
  99141. * @param meshes The mesh to target.
  99142. * @param radius Optional. If a cached radius position already exists, overrides default.
  99143. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99144. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99145. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99146. */
  99147. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  99148. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99149. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99150. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  99151. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  99152. for (var i = 0; i < meshes.length; i++) {
  99153. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  99154. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  99155. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  99156. }
  99157. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  99158. };
  99159. /**
  99160. * Targets the given mesh and updates zoom level accordingly.
  99161. * @param mesh The mesh to target.
  99162. * @param radius Optional. If a cached radius position already exists, overrides default.
  99163. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99164. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99165. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99166. */
  99167. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  99168. var _this = this;
  99169. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99170. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99171. var zoomTarget;
  99172. if (!this._attachedCamera) {
  99173. return;
  99174. }
  99175. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  99176. var bottom = minimumWorld.y;
  99177. var top = maximumWorld.y;
  99178. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  99179. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  99180. if (focusOnOriginXZ) {
  99181. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  99182. }
  99183. else {
  99184. var centerWorld = minimumWorld.add(radiusWorld);
  99185. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  99186. }
  99187. if (!this._vectorTransition) {
  99188. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  99189. }
  99190. this._betaIsAnimating = true;
  99191. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  99192. if (animatable) {
  99193. this._animatables.push(animatable);
  99194. }
  99195. // sets the radius and lower radius bounds
  99196. // Small delta ensures camera is not always at lower zoom limit.
  99197. var radius = 0;
  99198. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  99199. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99200. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  99201. radius = position;
  99202. }
  99203. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99204. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99205. if (this._attachedCamera.lowerRadiusLimit === null) {
  99206. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  99207. }
  99208. }
  99209. // Set sensibilities
  99210. var extend = maximumWorld.subtract(minimumWorld).length();
  99211. this._attachedCamera.panningSensibility = 5000 / extend;
  99212. this._attachedCamera.wheelPrecision = 100 / radius;
  99213. // transition to new radius
  99214. if (!this._radiusTransition) {
  99215. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99216. }
  99217. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  99218. _this.stopAllAnimations();
  99219. if (onAnimationEnd) {
  99220. onAnimationEnd();
  99221. }
  99222. if (_this._attachedCamera) {
  99223. _this._attachedCamera.storeState();
  99224. }
  99225. });
  99226. if (animatable) {
  99227. this._animatables.push(animatable);
  99228. }
  99229. };
  99230. /**
  99231. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  99232. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  99233. * frustum width.
  99234. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  99235. * to fully enclose the mesh in the viewing frustum.
  99236. */
  99237. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  99238. var size = maximumWorld.subtract(minimumWorld);
  99239. var boxVectorGlobalDiagonal = size.length();
  99240. var frustumSlope = this._getFrustumSlope();
  99241. // Formula for setting distance
  99242. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  99243. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  99244. // Horizon distance
  99245. var radius = radiusWithoutFraming * this._radiusScale;
  99246. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  99247. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  99248. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  99249. var camera = this._attachedCamera;
  99250. if (!camera) {
  99251. return 0;
  99252. }
  99253. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99254. // Don't exceed the requested limit
  99255. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  99256. }
  99257. // Don't exceed the upper radius limit
  99258. if (camera.upperRadiusLimit) {
  99259. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  99260. }
  99261. return distance;
  99262. };
  99263. /**
  99264. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  99265. * is automatically returned to its default position (expected to be above ground plane).
  99266. */
  99267. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  99268. var _this = this;
  99269. if (this._elevationReturnTime < 0) {
  99270. return;
  99271. }
  99272. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  99273. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  99274. var limitBeta = Math.PI * 0.5;
  99275. // Bring the camera back up if below the ground plane
  99276. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  99277. this._betaIsAnimating = true;
  99278. //Transition to new position
  99279. this.stopAllAnimations();
  99280. if (!this._betaTransition) {
  99281. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99282. }
  99283. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  99284. _this._clearAnimationLocks();
  99285. _this.stopAllAnimations();
  99286. });
  99287. if (animatabe) {
  99288. this._animatables.push(animatabe);
  99289. }
  99290. }
  99291. };
  99292. /**
  99293. * Returns the frustum slope based on the canvas ratio and camera FOV
  99294. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  99295. */
  99296. FramingBehavior.prototype._getFrustumSlope = function () {
  99297. // Calculate the viewport ratio
  99298. // Aspect Ratio is Height/Width.
  99299. var camera = this._attachedCamera;
  99300. if (!camera) {
  99301. return BABYLON.Vector2.Zero();
  99302. }
  99303. var engine = camera.getScene().getEngine();
  99304. var aspectRatio = engine.getAspectRatio(camera);
  99305. // Camera FOV is the vertical field of view (top-bottom) in radians.
  99306. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  99307. var frustumSlopeY = Math.tan(camera.fov / 2);
  99308. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  99309. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  99310. // along the forward vector.
  99311. var frustumSlopeX = frustumSlopeY * aspectRatio;
  99312. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  99313. };
  99314. /**
  99315. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  99316. */
  99317. FramingBehavior.prototype._clearAnimationLocks = function () {
  99318. this._betaIsAnimating = false;
  99319. };
  99320. /**
  99321. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99322. */
  99323. FramingBehavior.prototype._applyUserInteraction = function () {
  99324. if (this.isUserIsMoving) {
  99325. this._lastInteractionTime = BABYLON.Tools.Now;
  99326. this.stopAllAnimations();
  99327. this._clearAnimationLocks();
  99328. }
  99329. };
  99330. /**
  99331. * Stops and removes all animations that have been applied to the camera
  99332. */
  99333. FramingBehavior.prototype.stopAllAnimations = function () {
  99334. if (this._attachedCamera) {
  99335. this._attachedCamera.animations = [];
  99336. }
  99337. while (this._animatables.length) {
  99338. if (this._animatables[0]) {
  99339. this._animatables[0].onAnimationEnd = null;
  99340. this._animatables[0].stop();
  99341. }
  99342. this._animatables.shift();
  99343. }
  99344. };
  99345. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  99346. /**
  99347. * Gets a value indicating if the user is moving the camera
  99348. */
  99349. get: function () {
  99350. if (!this._attachedCamera) {
  99351. return false;
  99352. }
  99353. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99354. this._attachedCamera.inertialBetaOffset !== 0 ||
  99355. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99356. this._attachedCamera.inertialPanningX !== 0 ||
  99357. this._attachedCamera.inertialPanningY !== 0 ||
  99358. this._isPointerDown;
  99359. },
  99360. enumerable: true,
  99361. configurable: true
  99362. });
  99363. /**
  99364. * The easing function used by animations
  99365. */
  99366. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  99367. /**
  99368. * The easing mode used by animations
  99369. */
  99370. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  99371. // Statics
  99372. /**
  99373. * The camera can move all the way towards the mesh.
  99374. */
  99375. FramingBehavior.IgnoreBoundsSizeMode = 0;
  99376. /**
  99377. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  99378. */
  99379. FramingBehavior.FitFrustumSidesMode = 1;
  99380. return FramingBehavior;
  99381. }());
  99382. BABYLON.FramingBehavior = FramingBehavior;
  99383. })(BABYLON || (BABYLON = {}));
  99384. //# sourceMappingURL=babylon.framingBehavior.js.map
  99385. var BABYLON;
  99386. (function (BABYLON) {
  99387. /**
  99388. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  99389. */
  99390. var BouncingBehavior = /** @class */ (function () {
  99391. function BouncingBehavior() {
  99392. /**
  99393. * The duration of the animation, in milliseconds
  99394. */
  99395. this.transitionDuration = 450;
  99396. /**
  99397. * Length of the distance animated by the transition when lower radius is reached
  99398. */
  99399. this.lowerRadiusTransitionRange = 2;
  99400. /**
  99401. * Length of the distance animated by the transition when upper radius is reached
  99402. */
  99403. this.upperRadiusTransitionRange = -2;
  99404. this._autoTransitionRange = false;
  99405. // Animations
  99406. this._radiusIsAnimating = false;
  99407. this._radiusBounceTransition = null;
  99408. this._animatables = new Array();
  99409. }
  99410. Object.defineProperty(BouncingBehavior.prototype, "name", {
  99411. get: function () {
  99412. return "Bouncing";
  99413. },
  99414. enumerable: true,
  99415. configurable: true
  99416. });
  99417. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  99418. /**
  99419. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99420. */
  99421. get: function () {
  99422. return this._autoTransitionRange;
  99423. },
  99424. /**
  99425. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99426. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  99427. */
  99428. set: function (value) {
  99429. var _this = this;
  99430. if (this._autoTransitionRange === value) {
  99431. return;
  99432. }
  99433. this._autoTransitionRange = value;
  99434. var camera = this._attachedCamera;
  99435. if (!camera) {
  99436. return;
  99437. }
  99438. if (value) {
  99439. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99440. if (!mesh) {
  99441. return;
  99442. }
  99443. mesh.computeWorldMatrix(true);
  99444. var diagonal = mesh.getBoundingInfo().diagonalLength;
  99445. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  99446. _this.upperRadiusTransitionRange = diagonal * 0.05;
  99447. });
  99448. }
  99449. else if (this._onMeshTargetChangedObserver) {
  99450. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99451. }
  99452. },
  99453. enumerable: true,
  99454. configurable: true
  99455. });
  99456. BouncingBehavior.prototype.init = function () {
  99457. // Do notihng
  99458. };
  99459. BouncingBehavior.prototype.attach = function (camera) {
  99460. var _this = this;
  99461. this._attachedCamera = camera;
  99462. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99463. if (!_this._attachedCamera) {
  99464. return;
  99465. }
  99466. // Add the bounce animation to the lower radius limit
  99467. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  99468. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  99469. }
  99470. // Add the bounce animation to the upper radius limit
  99471. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  99472. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  99473. }
  99474. });
  99475. };
  99476. BouncingBehavior.prototype.detach = function () {
  99477. if (!this._attachedCamera) {
  99478. return;
  99479. }
  99480. if (this._onAfterCheckInputsObserver) {
  99481. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99482. }
  99483. if (this._onMeshTargetChangedObserver) {
  99484. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99485. }
  99486. this._attachedCamera = null;
  99487. };
  99488. /**
  99489. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  99490. * @param radiusLimit The limit to check against.
  99491. * @return Bool to indicate if at limit.
  99492. */
  99493. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  99494. if (!this._attachedCamera) {
  99495. return false;
  99496. }
  99497. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  99498. return true;
  99499. }
  99500. return false;
  99501. };
  99502. /**
  99503. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  99504. * @param radiusDelta The delta by which to animate to. Can be negative.
  99505. */
  99506. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  99507. var _this = this;
  99508. if (!this._attachedCamera) {
  99509. return;
  99510. }
  99511. if (!this._radiusBounceTransition) {
  99512. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  99513. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  99514. }
  99515. // Prevent zoom until bounce has completed
  99516. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  99517. this._attachedCamera.wheelPrecision = Infinity;
  99518. this._attachedCamera.inertialRadiusOffset = 0;
  99519. // Animate to the radius limit
  99520. this.stopAllAnimations();
  99521. this._radiusIsAnimating = true;
  99522. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  99523. if (animatable) {
  99524. this._animatables.push(animatable);
  99525. }
  99526. };
  99527. /**
  99528. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  99529. */
  99530. BouncingBehavior.prototype._clearAnimationLocks = function () {
  99531. this._radiusIsAnimating = false;
  99532. if (this._attachedCamera) {
  99533. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  99534. }
  99535. };
  99536. /**
  99537. * Stops and removes all animations that have been applied to the camera
  99538. */
  99539. BouncingBehavior.prototype.stopAllAnimations = function () {
  99540. if (this._attachedCamera) {
  99541. this._attachedCamera.animations = [];
  99542. }
  99543. while (this._animatables.length) {
  99544. this._animatables[0].onAnimationEnd = null;
  99545. this._animatables[0].stop();
  99546. this._animatables.shift();
  99547. }
  99548. };
  99549. /**
  99550. * The easing function used by animations
  99551. */
  99552. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  99553. /**
  99554. * The easing mode used by animations
  99555. */
  99556. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  99557. return BouncingBehavior;
  99558. }());
  99559. BABYLON.BouncingBehavior = BouncingBehavior;
  99560. })(BABYLON || (BABYLON = {}));
  99561. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  99562. var BABYLON;
  99563. (function (BABYLON) {
  99564. var AutoRotationBehavior = /** @class */ (function () {
  99565. function AutoRotationBehavior() {
  99566. this._zoomStopsAnimation = false;
  99567. this._idleRotationSpeed = 0.05;
  99568. this._idleRotationWaitTime = 2000;
  99569. this._idleRotationSpinupTime = 2000;
  99570. this._isPointerDown = false;
  99571. this._lastFrameTime = null;
  99572. this._lastInteractionTime = -Infinity;
  99573. this._cameraRotationSpeed = 0;
  99574. this._lastFrameRadius = 0;
  99575. }
  99576. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  99577. get: function () {
  99578. return "AutoRotation";
  99579. },
  99580. enumerable: true,
  99581. configurable: true
  99582. });
  99583. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  99584. /**
  99585. * Gets the flag that indicates if user zooming should stop animation.
  99586. */
  99587. get: function () {
  99588. return this._zoomStopsAnimation;
  99589. },
  99590. /**
  99591. * Sets the flag that indicates if user zooming should stop animation.
  99592. */
  99593. set: function (flag) {
  99594. this._zoomStopsAnimation = flag;
  99595. },
  99596. enumerable: true,
  99597. configurable: true
  99598. });
  99599. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  99600. /**
  99601. * Gets the default speed at which the camera rotates around the model.
  99602. */
  99603. get: function () {
  99604. return this._idleRotationSpeed;
  99605. },
  99606. /**
  99607. * Sets the default speed at which the camera rotates around the model.
  99608. */
  99609. set: function (speed) {
  99610. this._idleRotationSpeed = speed;
  99611. },
  99612. enumerable: true,
  99613. configurable: true
  99614. });
  99615. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  99616. /**
  99617. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  99618. */
  99619. get: function () {
  99620. return this._idleRotationWaitTime;
  99621. },
  99622. /**
  99623. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  99624. */
  99625. set: function (time) {
  99626. this._idleRotationWaitTime = time;
  99627. },
  99628. enumerable: true,
  99629. configurable: true
  99630. });
  99631. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  99632. /**
  99633. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99634. */
  99635. get: function () {
  99636. return this._idleRotationSpinupTime;
  99637. },
  99638. /**
  99639. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99640. */
  99641. set: function (time) {
  99642. this._idleRotationSpinupTime = time;
  99643. },
  99644. enumerable: true,
  99645. configurable: true
  99646. });
  99647. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  99648. /**
  99649. * Gets a value indicating if the camera is currently rotating because of this behavior
  99650. */
  99651. get: function () {
  99652. return Math.abs(this._cameraRotationSpeed) > 0;
  99653. },
  99654. enumerable: true,
  99655. configurable: true
  99656. });
  99657. AutoRotationBehavior.prototype.init = function () {
  99658. // Do notihng
  99659. };
  99660. AutoRotationBehavior.prototype.attach = function (camera) {
  99661. var _this = this;
  99662. this._attachedCamera = camera;
  99663. var scene = this._attachedCamera.getScene();
  99664. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99665. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99666. _this._isPointerDown = true;
  99667. return;
  99668. }
  99669. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99670. _this._isPointerDown = false;
  99671. }
  99672. });
  99673. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99674. var now = BABYLON.Tools.Now;
  99675. var dt = 0;
  99676. if (_this._lastFrameTime != null) {
  99677. dt = now - _this._lastFrameTime;
  99678. }
  99679. _this._lastFrameTime = now;
  99680. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99681. _this._applyUserInteraction();
  99682. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  99683. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  99684. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  99685. // Step camera rotation by rotation speed
  99686. if (_this._attachedCamera) {
  99687. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  99688. }
  99689. });
  99690. };
  99691. AutoRotationBehavior.prototype.detach = function () {
  99692. if (!this._attachedCamera) {
  99693. return;
  99694. }
  99695. var scene = this._attachedCamera.getScene();
  99696. if (this._onPrePointerObservableObserver) {
  99697. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99698. }
  99699. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99700. this._attachedCamera = null;
  99701. };
  99702. /**
  99703. * Returns true if user is scrolling.
  99704. * @return true if user is scrolling.
  99705. */
  99706. AutoRotationBehavior.prototype._userIsZooming = function () {
  99707. if (!this._attachedCamera) {
  99708. return false;
  99709. }
  99710. return this._attachedCamera.inertialRadiusOffset !== 0;
  99711. };
  99712. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  99713. if (!this._attachedCamera) {
  99714. return false;
  99715. }
  99716. var zoomHasHitLimit = false;
  99717. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  99718. zoomHasHitLimit = true;
  99719. }
  99720. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  99721. this._lastFrameRadius = this._attachedCamera.radius;
  99722. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  99723. };
  99724. /**
  99725. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99726. */
  99727. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  99728. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  99729. this._lastInteractionTime = BABYLON.Tools.Now;
  99730. }
  99731. };
  99732. // Tools
  99733. AutoRotationBehavior.prototype._userIsMoving = function () {
  99734. if (!this._attachedCamera) {
  99735. return false;
  99736. }
  99737. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99738. this._attachedCamera.inertialBetaOffset !== 0 ||
  99739. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99740. this._attachedCamera.inertialPanningX !== 0 ||
  99741. this._attachedCamera.inertialPanningY !== 0 ||
  99742. this._isPointerDown;
  99743. };
  99744. return AutoRotationBehavior;
  99745. }());
  99746. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  99747. })(BABYLON || (BABYLON = {}));
  99748. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  99749. var BABYLON;
  99750. (function (BABYLON) {
  99751. var NullEngineOptions = /** @class */ (function () {
  99752. function NullEngineOptions() {
  99753. this.renderWidth = 512;
  99754. this.renderHeight = 256;
  99755. this.textureSize = 512;
  99756. this.deterministicLockstep = false;
  99757. this.lockstepMaxSteps = 4;
  99758. }
  99759. return NullEngineOptions;
  99760. }());
  99761. BABYLON.NullEngineOptions = NullEngineOptions;
  99762. /**
  99763. * The null engine class provides support for headless version of babylon.js.
  99764. * This can be used in server side scenario or for testing purposes
  99765. */
  99766. var NullEngine = /** @class */ (function (_super) {
  99767. __extends(NullEngine, _super);
  99768. function NullEngine(options) {
  99769. if (options === void 0) { options = new NullEngineOptions(); }
  99770. var _this = _super.call(this, null) || this;
  99771. if (options.deterministicLockstep === undefined) {
  99772. options.deterministicLockstep = false;
  99773. }
  99774. if (options.lockstepMaxSteps === undefined) {
  99775. options.lockstepMaxSteps = 4;
  99776. }
  99777. _this._options = options;
  99778. // Init caps
  99779. // We consider we are on a webgl1 capable device
  99780. _this._caps = new BABYLON.EngineCapabilities();
  99781. _this._caps.maxTexturesImageUnits = 16;
  99782. _this._caps.maxVertexTextureImageUnits = 16;
  99783. _this._caps.maxTextureSize = 512;
  99784. _this._caps.maxCubemapTextureSize = 512;
  99785. _this._caps.maxRenderTextureSize = 512;
  99786. _this._caps.maxVertexAttribs = 16;
  99787. _this._caps.maxVaryingVectors = 16;
  99788. _this._caps.maxFragmentUniformVectors = 16;
  99789. _this._caps.maxVertexUniformVectors = 16;
  99790. // Extensions
  99791. _this._caps.standardDerivatives = false;
  99792. _this._caps.astc = null;
  99793. _this._caps.s3tc = null;
  99794. _this._caps.pvrtc = null;
  99795. _this._caps.etc1 = null;
  99796. _this._caps.etc2 = null;
  99797. _this._caps.textureAnisotropicFilterExtension = null;
  99798. _this._caps.maxAnisotropy = 0;
  99799. _this._caps.uintIndices = false;
  99800. _this._caps.fragmentDepthSupported = false;
  99801. _this._caps.highPrecisionShaderSupported = true;
  99802. _this._caps.colorBufferFloat = false;
  99803. _this._caps.textureFloat = false;
  99804. _this._caps.textureFloatLinearFiltering = false;
  99805. _this._caps.textureFloatRender = false;
  99806. _this._caps.textureHalfFloat = false;
  99807. _this._caps.textureHalfFloatLinearFiltering = false;
  99808. _this._caps.textureHalfFloatRender = false;
  99809. _this._caps.textureLOD = false;
  99810. _this._caps.drawBuffersExtension = false;
  99811. _this._caps.depthTextureExtension = false;
  99812. _this._caps.vertexArrayObject = false;
  99813. _this._caps.instancedArrays = false;
  99814. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  99815. // Wrappers
  99816. if (typeof URL === "undefined") {
  99817. URL = {
  99818. createObjectURL: function () { },
  99819. revokeObjectURL: function () { }
  99820. };
  99821. }
  99822. if (typeof Blob === "undefined") {
  99823. Blob = function () { };
  99824. }
  99825. return _this;
  99826. }
  99827. NullEngine.prototype.isDeterministicLockStep = function () {
  99828. return this._options.deterministicLockstep;
  99829. };
  99830. NullEngine.prototype.getLockstepMaxSteps = function () {
  99831. return this._options.lockstepMaxSteps;
  99832. };
  99833. NullEngine.prototype.getHardwareScalingLevel = function () {
  99834. return 1.0;
  99835. };
  99836. NullEngine.prototype.createVertexBuffer = function (vertices) {
  99837. return {
  99838. capacity: 0,
  99839. references: 1,
  99840. is32Bits: false
  99841. };
  99842. };
  99843. NullEngine.prototype.createIndexBuffer = function (indices) {
  99844. return {
  99845. capacity: 0,
  99846. references: 1,
  99847. is32Bits: false
  99848. };
  99849. };
  99850. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  99851. if (stencil === void 0) { stencil = false; }
  99852. };
  99853. NullEngine.prototype.getRenderWidth = function (useScreen) {
  99854. if (useScreen === void 0) { useScreen = false; }
  99855. if (!useScreen && this._currentRenderTarget) {
  99856. return this._currentRenderTarget.width;
  99857. }
  99858. return this._options.renderWidth;
  99859. };
  99860. NullEngine.prototype.getRenderHeight = function (useScreen) {
  99861. if (useScreen === void 0) { useScreen = false; }
  99862. if (!useScreen && this._currentRenderTarget) {
  99863. return this._currentRenderTarget.height;
  99864. }
  99865. return this._options.renderHeight;
  99866. };
  99867. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  99868. this._cachedViewport = viewport;
  99869. };
  99870. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  99871. return {
  99872. transformFeedback: null,
  99873. __SPECTOR_rebuildProgram: null
  99874. };
  99875. };
  99876. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  99877. return [];
  99878. };
  99879. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  99880. return [];
  99881. };
  99882. NullEngine.prototype.bindSamplers = function (effect) {
  99883. this._currentEffect = null;
  99884. };
  99885. NullEngine.prototype.enableEffect = function (effect) {
  99886. this._currentEffect = effect;
  99887. if (effect.onBind) {
  99888. effect.onBind(effect);
  99889. }
  99890. effect.onBindObservable.notifyObservers(effect);
  99891. };
  99892. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  99893. if (zOffset === void 0) { zOffset = 0; }
  99894. if (reverseSide === void 0) { reverseSide = false; }
  99895. };
  99896. NullEngine.prototype.setIntArray = function (uniform, array) {
  99897. };
  99898. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  99899. };
  99900. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  99901. };
  99902. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  99903. };
  99904. NullEngine.prototype.setFloatArray = function (uniform, array) {
  99905. };
  99906. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  99907. };
  99908. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  99909. };
  99910. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  99911. };
  99912. NullEngine.prototype.setArray = function (uniform, array) {
  99913. };
  99914. NullEngine.prototype.setArray2 = function (uniform, array) {
  99915. };
  99916. NullEngine.prototype.setArray3 = function (uniform, array) {
  99917. };
  99918. NullEngine.prototype.setArray4 = function (uniform, array) {
  99919. };
  99920. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  99921. };
  99922. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  99923. };
  99924. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  99925. };
  99926. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  99927. };
  99928. NullEngine.prototype.setFloat = function (uniform, value) {
  99929. };
  99930. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  99931. };
  99932. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  99933. };
  99934. NullEngine.prototype.setBool = function (uniform, bool) {
  99935. };
  99936. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  99937. };
  99938. NullEngine.prototype.setColor3 = function (uniform, color3) {
  99939. };
  99940. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  99941. };
  99942. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  99943. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  99944. if (this._alphaMode === mode) {
  99945. return;
  99946. }
  99947. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  99948. if (!noDepthWriteChange) {
  99949. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  99950. }
  99951. this._alphaMode = mode;
  99952. };
  99953. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  99954. };
  99955. NullEngine.prototype.wipeCaches = function (bruteForce) {
  99956. if (this.preventCacheWipeBetweenFrames) {
  99957. return;
  99958. }
  99959. this.resetTextureCache();
  99960. this._currentEffect = null;
  99961. if (bruteForce) {
  99962. this._currentProgram = null;
  99963. this._stencilState.reset();
  99964. this._depthCullingState.reset();
  99965. this._alphaState.reset();
  99966. }
  99967. this._cachedVertexBuffers = null;
  99968. this._cachedIndexBuffer = null;
  99969. this._cachedEffectForVertexBuffers = null;
  99970. };
  99971. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  99972. };
  99973. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  99974. };
  99975. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  99976. };
  99977. NullEngine.prototype._createTexture = function () {
  99978. return {};
  99979. };
  99980. NullEngine.prototype._releaseTexture = function (texture) {
  99981. };
  99982. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  99983. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99984. if (onLoad === void 0) { onLoad = null; }
  99985. if (onError === void 0) { onError = null; }
  99986. if (buffer === void 0) { buffer = null; }
  99987. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  99988. var url = String(urlArg);
  99989. texture.url = url;
  99990. texture.generateMipMaps = !noMipmap;
  99991. texture.samplingMode = samplingMode;
  99992. texture.invertY = invertY;
  99993. texture.baseWidth = this._options.textureSize;
  99994. texture.baseHeight = this._options.textureSize;
  99995. texture.width = this._options.textureSize;
  99996. texture.height = this._options.textureSize;
  99997. if (format) {
  99998. texture.format = format;
  99999. }
  100000. texture.isReady = true;
  100001. if (onLoad) {
  100002. onLoad();
  100003. }
  100004. this._internalTexturesCache.push(texture);
  100005. return texture;
  100006. };
  100007. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100008. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100009. if (options !== undefined && typeof options === "object") {
  100010. fullOptions.generateMipMaps = options.generateMipMaps;
  100011. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100012. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100013. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100014. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100015. }
  100016. else {
  100017. fullOptions.generateMipMaps = options;
  100018. fullOptions.generateDepthBuffer = true;
  100019. fullOptions.generateStencilBuffer = false;
  100020. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100021. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100022. }
  100023. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100024. var width = size.width || size;
  100025. var height = size.height || size;
  100026. texture._depthStencilBuffer = {};
  100027. texture._framebuffer = {};
  100028. texture.baseWidth = width;
  100029. texture.baseHeight = height;
  100030. texture.width = width;
  100031. texture.height = height;
  100032. texture.isReady = true;
  100033. texture.samples = 1;
  100034. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100035. texture.samplingMode = fullOptions.samplingMode;
  100036. texture.type = fullOptions.type;
  100037. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100038. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100039. this._internalTexturesCache.push(texture);
  100040. return texture;
  100041. };
  100042. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100043. texture.samplingMode = samplingMode;
  100044. };
  100045. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100046. if (this._currentRenderTarget) {
  100047. this.unBindFramebuffer(this._currentRenderTarget);
  100048. }
  100049. this._currentRenderTarget = texture;
  100050. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100051. if (this._cachedViewport && !forceFullscreenViewport) {
  100052. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100053. }
  100054. };
  100055. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100056. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  100057. this._currentRenderTarget = null;
  100058. if (onBeforeUnbind) {
  100059. if (texture._MSAAFramebuffer) {
  100060. this._currentFramebuffer = texture._framebuffer;
  100061. }
  100062. onBeforeUnbind();
  100063. }
  100064. this._currentFramebuffer = null;
  100065. };
  100066. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  100067. var vbo = {
  100068. capacity: 1,
  100069. references: 1,
  100070. is32Bits: false
  100071. };
  100072. return vbo;
  100073. };
  100074. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  100075. if (premulAlpha === void 0) { premulAlpha = false; }
  100076. };
  100077. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  100078. if (offset === void 0) { offset = 0; }
  100079. };
  100080. /**
  100081. * Updates a dynamic vertex buffer.
  100082. * @param vertexBuffer the vertex buffer to update
  100083. * @param data the data used to update the vertex buffer
  100084. * @param byteOffset the byte offset of the data (optional)
  100085. * @param byteLength the byte length of the data (optional)
  100086. */
  100087. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  100088. };
  100089. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  100090. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  100091. this._boundTexturesCache[this._activeChannel] = texture;
  100092. return true;
  100093. }
  100094. return false;
  100095. };
  100096. NullEngine.prototype._bindTexture = function (channel, texture) {
  100097. if (channel < 0) {
  100098. return;
  100099. }
  100100. this._bindTextureDirectly(0, texture);
  100101. };
  100102. NullEngine.prototype._releaseBuffer = function (buffer) {
  100103. buffer.references--;
  100104. if (buffer.references === 0) {
  100105. return true;
  100106. }
  100107. return false;
  100108. };
  100109. NullEngine.prototype.releaseEffects = function () {
  100110. };
  100111. NullEngine.prototype.displayLoadingUI = function () {
  100112. };
  100113. NullEngine.prototype.hideLoadingUI = function () {
  100114. };
  100115. return NullEngine;
  100116. }(BABYLON.Engine));
  100117. BABYLON.NullEngine = NullEngine;
  100118. })(BABYLON || (BABYLON = {}));
  100119. //# sourceMappingURL=babylon.nullEngine.js.map
  100120. var BABYLON;
  100121. (function (BABYLON) {
  100122. /**
  100123. * This class can be used to get instrumentation data from a Babylon engine
  100124. */
  100125. var EngineInstrumentation = /** @class */ (function () {
  100126. function EngineInstrumentation(engine) {
  100127. this.engine = engine;
  100128. this._captureGPUFrameTime = false;
  100129. this._gpuFrameTime = new BABYLON.PerfCounter();
  100130. this._captureShaderCompilationTime = false;
  100131. this._shaderCompilationTime = new BABYLON.PerfCounter();
  100132. // Observers
  100133. this._onBeginFrameObserver = null;
  100134. this._onEndFrameObserver = null;
  100135. this._onBeforeShaderCompilationObserver = null;
  100136. this._onAfterShaderCompilationObserver = null;
  100137. }
  100138. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  100139. // Properties
  100140. /**
  100141. * Gets the perf counter used for GPU frame time
  100142. */
  100143. get: function () {
  100144. return this._gpuFrameTime;
  100145. },
  100146. enumerable: true,
  100147. configurable: true
  100148. });
  100149. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  100150. /**
  100151. * Gets the GPU frame time capture status
  100152. */
  100153. get: function () {
  100154. return this._captureGPUFrameTime;
  100155. },
  100156. /**
  100157. * Enable or disable the GPU frame time capture
  100158. */
  100159. set: function (value) {
  100160. var _this = this;
  100161. if (value === this._captureGPUFrameTime) {
  100162. return;
  100163. }
  100164. this._captureGPUFrameTime = value;
  100165. if (value) {
  100166. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  100167. if (!_this._gpuFrameTimeToken) {
  100168. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  100169. }
  100170. });
  100171. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  100172. if (!_this._gpuFrameTimeToken) {
  100173. return;
  100174. }
  100175. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  100176. if (time > -1) {
  100177. _this._gpuFrameTimeToken = null;
  100178. _this._gpuFrameTime.fetchNewFrame();
  100179. _this._gpuFrameTime.addCount(time, true);
  100180. }
  100181. });
  100182. }
  100183. else {
  100184. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100185. this._onBeginFrameObserver = null;
  100186. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100187. this._onEndFrameObserver = null;
  100188. }
  100189. },
  100190. enumerable: true,
  100191. configurable: true
  100192. });
  100193. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  100194. /**
  100195. * Gets the perf counter used for shader compilation time
  100196. */
  100197. get: function () {
  100198. return this._shaderCompilationTime;
  100199. },
  100200. enumerable: true,
  100201. configurable: true
  100202. });
  100203. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  100204. /**
  100205. * Gets the shader compilation time capture status
  100206. */
  100207. get: function () {
  100208. return this._captureShaderCompilationTime;
  100209. },
  100210. /**
  100211. * Enable or disable the shader compilation time capture
  100212. */
  100213. set: function (value) {
  100214. var _this = this;
  100215. if (value === this._captureShaderCompilationTime) {
  100216. return;
  100217. }
  100218. this._captureShaderCompilationTime = value;
  100219. if (value) {
  100220. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  100221. _this._shaderCompilationTime.fetchNewFrame();
  100222. _this._shaderCompilationTime.beginMonitoring();
  100223. });
  100224. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  100225. _this._shaderCompilationTime.endMonitoring();
  100226. });
  100227. }
  100228. else {
  100229. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100230. this._onBeforeShaderCompilationObserver = null;
  100231. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100232. this._onAfterShaderCompilationObserver = null;
  100233. }
  100234. },
  100235. enumerable: true,
  100236. configurable: true
  100237. });
  100238. EngineInstrumentation.prototype.dispose = function () {
  100239. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100240. this._onBeginFrameObserver = null;
  100241. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100242. this._onEndFrameObserver = null;
  100243. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100244. this._onBeforeShaderCompilationObserver = null;
  100245. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100246. this._onAfterShaderCompilationObserver = null;
  100247. this.engine = null;
  100248. };
  100249. return EngineInstrumentation;
  100250. }());
  100251. BABYLON.EngineInstrumentation = EngineInstrumentation;
  100252. })(BABYLON || (BABYLON = {}));
  100253. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  100254. var BABYLON;
  100255. (function (BABYLON) {
  100256. /**
  100257. * This class can be used to get instrumentation data from a Babylon engine
  100258. */
  100259. var SceneInstrumentation = /** @class */ (function () {
  100260. function SceneInstrumentation(scene) {
  100261. var _this = this;
  100262. this.scene = scene;
  100263. this._captureActiveMeshesEvaluationTime = false;
  100264. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  100265. this._captureRenderTargetsRenderTime = false;
  100266. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  100267. this._captureFrameTime = false;
  100268. this._frameTime = new BABYLON.PerfCounter();
  100269. this._captureRenderTime = false;
  100270. this._renderTime = new BABYLON.PerfCounter();
  100271. this._captureInterFrameTime = false;
  100272. this._interFrameTime = new BABYLON.PerfCounter();
  100273. this._captureParticlesRenderTime = false;
  100274. this._particlesRenderTime = new BABYLON.PerfCounter();
  100275. this._captureSpritesRenderTime = false;
  100276. this._spritesRenderTime = new BABYLON.PerfCounter();
  100277. this._capturePhysicsTime = false;
  100278. this._physicsTime = new BABYLON.PerfCounter();
  100279. this._captureAnimationsTime = false;
  100280. this._animationsTime = new BABYLON.PerfCounter();
  100281. this._captureCameraRenderTime = false;
  100282. this._cameraRenderTime = new BABYLON.PerfCounter();
  100283. // Observers
  100284. this._onBeforeActiveMeshesEvaluationObserver = null;
  100285. this._onAfterActiveMeshesEvaluationObserver = null;
  100286. this._onBeforeRenderTargetsRenderObserver = null;
  100287. this._onAfterRenderTargetsRenderObserver = null;
  100288. this._onAfterRenderObserver = null;
  100289. this._onBeforeDrawPhaseObserver = null;
  100290. this._onAfterDrawPhaseObserver = null;
  100291. this._onBeforeAnimationsObserver = null;
  100292. this._onBeforeParticlesRenderingObserver = null;
  100293. this._onAfterParticlesRenderingObserver = null;
  100294. this._onBeforeSpritesRenderingObserver = null;
  100295. this._onAfterSpritesRenderingObserver = null;
  100296. this._onBeforePhysicsObserver = null;
  100297. this._onAfterPhysicsObserver = null;
  100298. this._onAfterAnimationsObserver = null;
  100299. this._onBeforeCameraRenderObserver = null;
  100300. this._onAfterCameraRenderObserver = null;
  100301. // Before render
  100302. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  100303. if (_this._captureActiveMeshesEvaluationTime) {
  100304. _this._activeMeshesEvaluationTime.fetchNewFrame();
  100305. }
  100306. if (_this._captureRenderTargetsRenderTime) {
  100307. _this._renderTargetsRenderTime.fetchNewFrame();
  100308. }
  100309. if (_this._captureFrameTime) {
  100310. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  100311. _this._frameTime.beginMonitoring();
  100312. }
  100313. if (_this._captureInterFrameTime) {
  100314. _this._interFrameTime.endMonitoring();
  100315. }
  100316. if (_this._captureParticlesRenderTime) {
  100317. _this._particlesRenderTime.fetchNewFrame();
  100318. }
  100319. if (_this._captureSpritesRenderTime) {
  100320. _this._spritesRenderTime.fetchNewFrame();
  100321. }
  100322. if (_this._captureAnimationsTime) {
  100323. _this._animationsTime.beginMonitoring();
  100324. }
  100325. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  100326. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  100327. });
  100328. // After render
  100329. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  100330. if (_this._captureFrameTime) {
  100331. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  100332. _this._frameTime.endMonitoring();
  100333. }
  100334. if (_this._captureRenderTime) {
  100335. _this._renderTime.endMonitoring(false);
  100336. }
  100337. if (_this._captureInterFrameTime) {
  100338. _this._interFrameTime.beginMonitoring();
  100339. }
  100340. });
  100341. }
  100342. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  100343. // Properties
  100344. /**
  100345. * Gets the perf counter used for active meshes evaluation time
  100346. */
  100347. get: function () {
  100348. return this._activeMeshesEvaluationTime;
  100349. },
  100350. enumerable: true,
  100351. configurable: true
  100352. });
  100353. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  100354. /**
  100355. * Gets the active meshes evaluation time capture status
  100356. */
  100357. get: function () {
  100358. return this._captureActiveMeshesEvaluationTime;
  100359. },
  100360. /**
  100361. * Enable or disable the active meshes evaluation time capture
  100362. */
  100363. set: function (value) {
  100364. var _this = this;
  100365. if (value === this._captureActiveMeshesEvaluationTime) {
  100366. return;
  100367. }
  100368. this._captureActiveMeshesEvaluationTime = value;
  100369. if (value) {
  100370. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  100371. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  100372. _this._activeMeshesEvaluationTime.beginMonitoring();
  100373. });
  100374. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  100375. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  100376. _this._activeMeshesEvaluationTime.endMonitoring();
  100377. });
  100378. }
  100379. else {
  100380. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100381. this._onBeforeActiveMeshesEvaluationObserver = null;
  100382. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100383. this._onAfterActiveMeshesEvaluationObserver = null;
  100384. }
  100385. },
  100386. enumerable: true,
  100387. configurable: true
  100388. });
  100389. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  100390. /**
  100391. * Gets the perf counter used for render targets render time
  100392. */
  100393. get: function () {
  100394. return this._renderTargetsRenderTime;
  100395. },
  100396. enumerable: true,
  100397. configurable: true
  100398. });
  100399. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  100400. /**
  100401. * Gets the render targets render time capture status
  100402. */
  100403. get: function () {
  100404. return this._captureRenderTargetsRenderTime;
  100405. },
  100406. /**
  100407. * Enable or disable the render targets render time capture
  100408. */
  100409. set: function (value) {
  100410. var _this = this;
  100411. if (value === this._captureRenderTargetsRenderTime) {
  100412. return;
  100413. }
  100414. this._captureRenderTargetsRenderTime = value;
  100415. if (value) {
  100416. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  100417. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  100418. _this._renderTargetsRenderTime.beginMonitoring();
  100419. });
  100420. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  100421. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  100422. _this._renderTargetsRenderTime.endMonitoring(false);
  100423. });
  100424. }
  100425. else {
  100426. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100427. this._onBeforeRenderTargetsRenderObserver = null;
  100428. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100429. this._onAfterRenderTargetsRenderObserver = null;
  100430. }
  100431. },
  100432. enumerable: true,
  100433. configurable: true
  100434. });
  100435. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  100436. /**
  100437. * Gets the perf counter used for particles render time
  100438. */
  100439. get: function () {
  100440. return this._particlesRenderTime;
  100441. },
  100442. enumerable: true,
  100443. configurable: true
  100444. });
  100445. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  100446. /**
  100447. * Gets the particles render time capture status
  100448. */
  100449. get: function () {
  100450. return this._captureParticlesRenderTime;
  100451. },
  100452. /**
  100453. * Enable or disable the particles render time capture
  100454. */
  100455. set: function (value) {
  100456. var _this = this;
  100457. if (value === this._captureParticlesRenderTime) {
  100458. return;
  100459. }
  100460. this._captureParticlesRenderTime = value;
  100461. if (value) {
  100462. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  100463. BABYLON.Tools.StartPerformanceCounter("Particles");
  100464. _this._particlesRenderTime.beginMonitoring();
  100465. });
  100466. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  100467. BABYLON.Tools.EndPerformanceCounter("Particles");
  100468. _this._particlesRenderTime.endMonitoring(false);
  100469. });
  100470. }
  100471. else {
  100472. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100473. this._onBeforeParticlesRenderingObserver = null;
  100474. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100475. this._onAfterParticlesRenderingObserver = null;
  100476. }
  100477. },
  100478. enumerable: true,
  100479. configurable: true
  100480. });
  100481. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  100482. /**
  100483. * Gets the perf counter used for sprites render time
  100484. */
  100485. get: function () {
  100486. return this._spritesRenderTime;
  100487. },
  100488. enumerable: true,
  100489. configurable: true
  100490. });
  100491. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  100492. /**
  100493. * Gets the sprites render time capture status
  100494. */
  100495. get: function () {
  100496. return this._captureSpritesRenderTime;
  100497. },
  100498. /**
  100499. * Enable or disable the sprites render time capture
  100500. */
  100501. set: function (value) {
  100502. var _this = this;
  100503. if (value === this._captureSpritesRenderTime) {
  100504. return;
  100505. }
  100506. this._captureSpritesRenderTime = value;
  100507. if (value) {
  100508. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  100509. BABYLON.Tools.StartPerformanceCounter("Sprites");
  100510. _this._spritesRenderTime.beginMonitoring();
  100511. });
  100512. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  100513. BABYLON.Tools.EndPerformanceCounter("Sprites");
  100514. _this._spritesRenderTime.endMonitoring(false);
  100515. });
  100516. }
  100517. else {
  100518. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100519. this._onBeforeSpritesRenderingObserver = null;
  100520. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100521. this._onAfterSpritesRenderingObserver = null;
  100522. }
  100523. },
  100524. enumerable: true,
  100525. configurable: true
  100526. });
  100527. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  100528. /**
  100529. * Gets the perf counter used for physics time
  100530. */
  100531. get: function () {
  100532. return this._physicsTime;
  100533. },
  100534. enumerable: true,
  100535. configurable: true
  100536. });
  100537. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  100538. /**
  100539. * Gets the physics time capture status
  100540. */
  100541. get: function () {
  100542. return this._capturePhysicsTime;
  100543. },
  100544. /**
  100545. * Enable or disable the physics time capture
  100546. */
  100547. set: function (value) {
  100548. var _this = this;
  100549. if (value === this._capturePhysicsTime) {
  100550. return;
  100551. }
  100552. this._capturePhysicsTime = value;
  100553. if (value) {
  100554. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  100555. BABYLON.Tools.StartPerformanceCounter("Physics");
  100556. _this._physicsTime.beginMonitoring();
  100557. });
  100558. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  100559. BABYLON.Tools.EndPerformanceCounter("Physics");
  100560. _this._physicsTime.endMonitoring();
  100561. });
  100562. }
  100563. else {
  100564. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  100565. this._onBeforePhysicsObserver = null;
  100566. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  100567. this._onAfterPhysicsObserver = null;
  100568. }
  100569. },
  100570. enumerable: true,
  100571. configurable: true
  100572. });
  100573. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  100574. /**
  100575. * Gets the perf counter used for animations time
  100576. */
  100577. get: function () {
  100578. return this._animationsTime;
  100579. },
  100580. enumerable: true,
  100581. configurable: true
  100582. });
  100583. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  100584. /**
  100585. * Gets the animations time capture status
  100586. */
  100587. get: function () {
  100588. return this._captureAnimationsTime;
  100589. },
  100590. /**
  100591. * Enable or disable the animations time capture
  100592. */
  100593. set: function (value) {
  100594. var _this = this;
  100595. if (value === this._captureAnimationsTime) {
  100596. return;
  100597. }
  100598. this._captureAnimationsTime = value;
  100599. if (value) {
  100600. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  100601. _this._animationsTime.endMonitoring();
  100602. });
  100603. }
  100604. else {
  100605. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100606. this._onAfterAnimationsObserver = null;
  100607. }
  100608. },
  100609. enumerable: true,
  100610. configurable: true
  100611. });
  100612. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  100613. /**
  100614. * Gets the perf counter used for frame time capture
  100615. */
  100616. get: function () {
  100617. return this._frameTime;
  100618. },
  100619. enumerable: true,
  100620. configurable: true
  100621. });
  100622. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  100623. /**
  100624. * Gets the frame time capture status
  100625. */
  100626. get: function () {
  100627. return this._captureFrameTime;
  100628. },
  100629. /**
  100630. * Enable or disable the frame time capture
  100631. */
  100632. set: function (value) {
  100633. this._captureFrameTime = value;
  100634. },
  100635. enumerable: true,
  100636. configurable: true
  100637. });
  100638. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  100639. /**
  100640. * Gets the perf counter used for inter-frames time capture
  100641. */
  100642. get: function () {
  100643. return this._interFrameTime;
  100644. },
  100645. enumerable: true,
  100646. configurable: true
  100647. });
  100648. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  100649. /**
  100650. * Gets the inter-frames time capture status
  100651. */
  100652. get: function () {
  100653. return this._captureInterFrameTime;
  100654. },
  100655. /**
  100656. * Enable or disable the inter-frames time capture
  100657. */
  100658. set: function (value) {
  100659. this._captureInterFrameTime = value;
  100660. },
  100661. enumerable: true,
  100662. configurable: true
  100663. });
  100664. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  100665. /**
  100666. * Gets the perf counter used for render time capture
  100667. */
  100668. get: function () {
  100669. return this._renderTime;
  100670. },
  100671. enumerable: true,
  100672. configurable: true
  100673. });
  100674. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  100675. /**
  100676. * Gets the render time capture status
  100677. */
  100678. get: function () {
  100679. return this._captureRenderTime;
  100680. },
  100681. /**
  100682. * Enable or disable the render time capture
  100683. */
  100684. set: function (value) {
  100685. var _this = this;
  100686. if (value === this._captureRenderTime) {
  100687. return;
  100688. }
  100689. this._captureRenderTime = value;
  100690. if (value) {
  100691. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  100692. _this._renderTime.beginMonitoring();
  100693. BABYLON.Tools.StartPerformanceCounter("Main render");
  100694. });
  100695. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  100696. _this._renderTime.endMonitoring(false);
  100697. BABYLON.Tools.EndPerformanceCounter("Main render");
  100698. });
  100699. }
  100700. else {
  100701. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100702. this._onBeforeDrawPhaseObserver = null;
  100703. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100704. this._onAfterDrawPhaseObserver = null;
  100705. }
  100706. },
  100707. enumerable: true,
  100708. configurable: true
  100709. });
  100710. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  100711. /**
  100712. * Gets the perf counter used for camera render time capture
  100713. */
  100714. get: function () {
  100715. return this._cameraRenderTime;
  100716. },
  100717. enumerable: true,
  100718. configurable: true
  100719. });
  100720. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  100721. /**
  100722. * Gets the camera render time capture status
  100723. */
  100724. get: function () {
  100725. return this._captureCameraRenderTime;
  100726. },
  100727. /**
  100728. * Enable or disable the camera render time capture
  100729. */
  100730. set: function (value) {
  100731. var _this = this;
  100732. if (value === this._captureCameraRenderTime) {
  100733. return;
  100734. }
  100735. this._captureCameraRenderTime = value;
  100736. if (value) {
  100737. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  100738. _this._cameraRenderTime.beginMonitoring();
  100739. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  100740. });
  100741. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  100742. _this._cameraRenderTime.endMonitoring(false);
  100743. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  100744. });
  100745. }
  100746. else {
  100747. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100748. this._onBeforeCameraRenderObserver = null;
  100749. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100750. this._onAfterCameraRenderObserver = null;
  100751. }
  100752. },
  100753. enumerable: true,
  100754. configurable: true
  100755. });
  100756. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  100757. /**
  100758. * Gets the perf counter used for draw calls
  100759. */
  100760. get: function () {
  100761. return this.scene.getEngine()._drawCalls;
  100762. },
  100763. enumerable: true,
  100764. configurable: true
  100765. });
  100766. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  100767. /**
  100768. * Gets the perf counter used for texture collisions
  100769. */
  100770. get: function () {
  100771. return this.scene.getEngine()._textureCollisions;
  100772. },
  100773. enumerable: true,
  100774. configurable: true
  100775. });
  100776. SceneInstrumentation.prototype.dispose = function () {
  100777. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100778. this._onAfterRenderObserver = null;
  100779. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100780. this._onBeforeActiveMeshesEvaluationObserver = null;
  100781. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100782. this._onAfterActiveMeshesEvaluationObserver = null;
  100783. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100784. this._onBeforeRenderTargetsRenderObserver = null;
  100785. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100786. this._onAfterRenderTargetsRenderObserver = null;
  100787. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  100788. this._onBeforeAnimationsObserver = null;
  100789. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100790. this._onBeforeParticlesRenderingObserver = null;
  100791. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100792. this._onAfterParticlesRenderingObserver = null;
  100793. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100794. this._onBeforeSpritesRenderingObserver = null;
  100795. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100796. this._onAfterSpritesRenderingObserver = null;
  100797. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100798. this._onBeforeDrawPhaseObserver = null;
  100799. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100800. this._onAfterDrawPhaseObserver = null;
  100801. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  100802. this._onBeforePhysicsObserver = null;
  100803. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  100804. this._onAfterPhysicsObserver = null;
  100805. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100806. this._onAfterAnimationsObserver = null;
  100807. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100808. this._onBeforeCameraRenderObserver = null;
  100809. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100810. this._onAfterCameraRenderObserver = null;
  100811. this.scene = null;
  100812. };
  100813. return SceneInstrumentation;
  100814. }());
  100815. BABYLON.SceneInstrumentation = SceneInstrumentation;
  100816. })(BABYLON || (BABYLON = {}));
  100817. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  100818. var BABYLON;
  100819. (function (BABYLON) {
  100820. /**
  100821. * @hidden
  100822. **/
  100823. var _TimeToken = /** @class */ (function () {
  100824. function _TimeToken() {
  100825. this._timeElapsedQueryEnded = false;
  100826. }
  100827. return _TimeToken;
  100828. }());
  100829. BABYLON._TimeToken = _TimeToken;
  100830. })(BABYLON || (BABYLON = {}));
  100831. //# sourceMappingURL=babylon.timeToken.js.map
  100832. var BABYLON;
  100833. (function (BABYLON) {
  100834. /**
  100835. * Background material defines definition.
  100836. * @hidden Mainly internal Use
  100837. */
  100838. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  100839. __extends(BackgroundMaterialDefines, _super);
  100840. /**
  100841. * Constructor of the defines.
  100842. */
  100843. function BackgroundMaterialDefines() {
  100844. var _this = _super.call(this) || this;
  100845. /**
  100846. * True if the diffuse texture is in use.
  100847. */
  100848. _this.DIFFUSE = false;
  100849. /**
  100850. * The direct UV channel to use.
  100851. */
  100852. _this.DIFFUSEDIRECTUV = 0;
  100853. /**
  100854. * True if the diffuse texture is in gamma space.
  100855. */
  100856. _this.GAMMADIFFUSE = false;
  100857. /**
  100858. * True if the diffuse texture has opacity in the alpha channel.
  100859. */
  100860. _this.DIFFUSEHASALPHA = false;
  100861. /**
  100862. * True if you want the material to fade to transparent at grazing angle.
  100863. */
  100864. _this.OPACITYFRESNEL = false;
  100865. /**
  100866. * True if an extra blur needs to be added in the reflection.
  100867. */
  100868. _this.REFLECTIONBLUR = false;
  100869. /**
  100870. * True if you want the material to fade to reflection at grazing angle.
  100871. */
  100872. _this.REFLECTIONFRESNEL = false;
  100873. /**
  100874. * True if you want the material to falloff as far as you move away from the scene center.
  100875. */
  100876. _this.REFLECTIONFALLOFF = false;
  100877. /**
  100878. * False if the current Webgl implementation does not support the texture lod extension.
  100879. */
  100880. _this.TEXTURELODSUPPORT = false;
  100881. /**
  100882. * True to ensure the data are premultiplied.
  100883. */
  100884. _this.PREMULTIPLYALPHA = false;
  100885. /**
  100886. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  100887. */
  100888. _this.USERGBCOLOR = false;
  100889. /**
  100890. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  100891. * stays aligned with the desired configuration.
  100892. */
  100893. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  100894. /**
  100895. * True to add noise in order to reduce the banding effect.
  100896. */
  100897. _this.NOISE = false;
  100898. /**
  100899. * is the reflection texture in BGR color scheme?
  100900. * Mainly used to solve a bug in ios10 video tag
  100901. */
  100902. _this.REFLECTIONBGR = false;
  100903. _this.IMAGEPROCESSING = false;
  100904. _this.VIGNETTE = false;
  100905. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  100906. _this.VIGNETTEBLENDMODEOPAQUE = false;
  100907. _this.TONEMAPPING = false;
  100908. _this.CONTRAST = false;
  100909. _this.COLORCURVES = false;
  100910. _this.COLORGRADING = false;
  100911. _this.COLORGRADING3D = false;
  100912. _this.SAMPLER3DGREENDEPTH = false;
  100913. _this.SAMPLER3DBGRMAP = false;
  100914. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  100915. _this.EXPOSURE = false;
  100916. // Reflection.
  100917. _this.REFLECTION = false;
  100918. _this.REFLECTIONMAP_3D = false;
  100919. _this.REFLECTIONMAP_SPHERICAL = false;
  100920. _this.REFLECTIONMAP_PLANAR = false;
  100921. _this.REFLECTIONMAP_CUBIC = false;
  100922. _this.REFLECTIONMAP_PROJECTION = false;
  100923. _this.REFLECTIONMAP_SKYBOX = false;
  100924. _this.REFLECTIONMAP_EXPLICIT = false;
  100925. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100926. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100927. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100928. _this.INVERTCUBICMAP = false;
  100929. _this.REFLECTIONMAP_OPPOSITEZ = false;
  100930. _this.LODINREFLECTIONALPHA = false;
  100931. _this.GAMMAREFLECTION = false;
  100932. _this.RGBDREFLECTION = false;
  100933. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  100934. // Default BJS.
  100935. _this.MAINUV1 = false;
  100936. _this.MAINUV2 = false;
  100937. _this.UV1 = false;
  100938. _this.UV2 = false;
  100939. _this.CLIPPLANE = false;
  100940. _this.POINTSIZE = false;
  100941. _this.FOG = false;
  100942. _this.NORMAL = false;
  100943. _this.NUM_BONE_INFLUENCERS = 0;
  100944. _this.BonesPerMesh = 0;
  100945. _this.INSTANCES = false;
  100946. _this.SHADOWFLOAT = false;
  100947. _this.rebuild();
  100948. return _this;
  100949. }
  100950. return BackgroundMaterialDefines;
  100951. }(BABYLON.MaterialDefines));
  100952. /**
  100953. * Background material used to create an efficient environement around your scene.
  100954. */
  100955. var BackgroundMaterial = /** @class */ (function (_super) {
  100956. __extends(BackgroundMaterial, _super);
  100957. /**
  100958. * Instantiates a Background Material in the given scene
  100959. * @param name The friendly name of the material
  100960. * @param scene The scene to add the material to
  100961. */
  100962. function BackgroundMaterial(name, scene) {
  100963. var _this = _super.call(this, name, scene) || this;
  100964. /**
  100965. * Key light Color (multiply against the environement texture)
  100966. */
  100967. _this.primaryColor = BABYLON.Color3.White();
  100968. _this._primaryColorShadowLevel = 0;
  100969. _this._primaryColorHighlightLevel = 0;
  100970. /**
  100971. * Reflection Texture used in the material.
  100972. * Should be author in a specific way for the best result (refer to the documentation).
  100973. */
  100974. _this.reflectionTexture = null;
  100975. /**
  100976. * Reflection Texture level of blur.
  100977. *
  100978. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  100979. * texture twice.
  100980. */
  100981. _this.reflectionBlur = 0;
  100982. /**
  100983. * Diffuse Texture used in the material.
  100984. * Should be author in a specific way for the best result (refer to the documentation).
  100985. */
  100986. _this.diffuseTexture = null;
  100987. _this._shadowLights = null;
  100988. /**
  100989. * Specify the list of lights casting shadow on the material.
  100990. * All scene shadow lights will be included if null.
  100991. */
  100992. _this.shadowLights = null;
  100993. /**
  100994. * Helps adjusting the shadow to a softer level if required.
  100995. * 0 means black shadows and 1 means no shadows.
  100996. */
  100997. _this.shadowLevel = 0;
  100998. /**
  100999. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101000. * It is usually zero but might be interesting to modify according to your setup.
  101001. */
  101002. _this.sceneCenter = BABYLON.Vector3.Zero();
  101003. /**
  101004. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101005. * This helps ensuring a nice transition when the camera goes under the ground.
  101006. */
  101007. _this.opacityFresnel = true;
  101008. /**
  101009. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101010. * This helps adding a mirror texture on the ground.
  101011. */
  101012. _this.reflectionFresnel = false;
  101013. /**
  101014. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101015. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101016. */
  101017. _this.reflectionFalloffDistance = 0.0;
  101018. /**
  101019. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101020. */
  101021. _this.reflectionAmount = 1.0;
  101022. /**
  101023. * This specifies the weight of the reflection at grazing angle.
  101024. */
  101025. _this.reflectionReflectance0 = 0.05;
  101026. /**
  101027. * This specifies the weight of the reflection at a perpendicular point of view.
  101028. */
  101029. _this.reflectionReflectance90 = 0.5;
  101030. /**
  101031. * Helps to directly use the maps channels instead of their level.
  101032. */
  101033. _this.useRGBColor = true;
  101034. /**
  101035. * This helps reducing the banding effect that could occur on the background.
  101036. */
  101037. _this.enableNoise = false;
  101038. _this._fovMultiplier = 1.0;
  101039. /**
  101040. * Enable the FOV adjustment feature controlled by fovMultiplier.
  101041. */
  101042. _this.useEquirectangularFOV = false;
  101043. _this._maxSimultaneousLights = 4;
  101044. /**
  101045. * Number of Simultaneous lights allowed on the material.
  101046. */
  101047. _this.maxSimultaneousLights = 4;
  101048. /**
  101049. * Keep track of the image processing observer to allow dispose and replace.
  101050. */
  101051. _this._imageProcessingObserver = null;
  101052. /**
  101053. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  101054. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  101055. */
  101056. _this.switchToBGR = false;
  101057. // Temp values kept as cache in the material.
  101058. _this._renderTargets = new BABYLON.SmartArray(16);
  101059. _this._reflectionControls = BABYLON.Vector4.Zero();
  101060. _this._white = BABYLON.Color3.White();
  101061. _this._primaryShadowColor = BABYLON.Color3.Black();
  101062. _this._primaryHighlightColor = BABYLON.Color3.Black();
  101063. // Setup the default processing configuration to the scene.
  101064. _this._attachImageProcessingConfiguration(null);
  101065. _this.getRenderTargetTextures = function () {
  101066. _this._renderTargets.reset();
  101067. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  101068. _this._renderTargets.push(_this._diffuseTexture);
  101069. }
  101070. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  101071. _this._renderTargets.push(_this._reflectionTexture);
  101072. }
  101073. return _this._renderTargets;
  101074. };
  101075. return _this;
  101076. }
  101077. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  101078. /**
  101079. * Experimental Internal Use Only.
  101080. *
  101081. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  101082. * This acts as a helper to set the primary color to a more "human friendly" value.
  101083. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  101084. * output color as close as possible from the chosen value.
  101085. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  101086. * part of lighting setup.)
  101087. */
  101088. get: function () {
  101089. return this.__perceptualColor;
  101090. },
  101091. set: function (value) {
  101092. this.__perceptualColor = value;
  101093. this._computePrimaryColorFromPerceptualColor();
  101094. this._markAllSubMeshesAsLightsDirty();
  101095. },
  101096. enumerable: true,
  101097. configurable: true
  101098. });
  101099. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  101100. /**
  101101. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  101102. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  101103. */
  101104. get: function () {
  101105. return this._primaryColorShadowLevel;
  101106. },
  101107. set: function (value) {
  101108. this._primaryColorShadowLevel = value;
  101109. this._computePrimaryColors();
  101110. this._markAllSubMeshesAsLightsDirty();
  101111. },
  101112. enumerable: true,
  101113. configurable: true
  101114. });
  101115. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  101116. /**
  101117. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  101118. * The primary color is used at the level chosen to define what the white area would look.
  101119. */
  101120. get: function () {
  101121. return this._primaryColorHighlightLevel;
  101122. },
  101123. set: function (value) {
  101124. this._primaryColorHighlightLevel = value;
  101125. this._computePrimaryColors();
  101126. this._markAllSubMeshesAsLightsDirty();
  101127. },
  101128. enumerable: true,
  101129. configurable: true
  101130. });
  101131. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  101132. /**
  101133. * Sets the reflection reflectance fresnel values according to the default standard
  101134. * empirically know to work well :-)
  101135. */
  101136. set: function (value) {
  101137. var reflectionWeight = value;
  101138. if (reflectionWeight < 0.5) {
  101139. reflectionWeight = reflectionWeight * 2.0;
  101140. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  101141. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  101142. }
  101143. else {
  101144. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  101145. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  101146. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  101147. }
  101148. },
  101149. enumerable: true,
  101150. configurable: true
  101151. });
  101152. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  101153. /**
  101154. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101155. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  101156. * Recommended to be keep at 1.0 except for special cases.
  101157. */
  101158. get: function () {
  101159. return this._fovMultiplier;
  101160. },
  101161. set: function (value) {
  101162. if (isNaN(value)) {
  101163. value = 1.0;
  101164. }
  101165. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  101166. },
  101167. enumerable: true,
  101168. configurable: true
  101169. });
  101170. /**
  101171. * Attaches a new image processing configuration to the PBR Material.
  101172. * @param configuration (if null the scene configuration will be use)
  101173. */
  101174. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  101175. var _this = this;
  101176. if (configuration === this._imageProcessingConfiguration) {
  101177. return;
  101178. }
  101179. // Detaches observer.
  101180. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101181. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101182. }
  101183. // Pick the scene configuration if needed.
  101184. if (!configuration) {
  101185. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  101186. }
  101187. else {
  101188. this._imageProcessingConfiguration = configuration;
  101189. }
  101190. // Attaches observer.
  101191. if (this._imageProcessingConfiguration) {
  101192. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  101193. _this._computePrimaryColorFromPerceptualColor();
  101194. _this._markAllSubMeshesAsImageProcessingDirty();
  101195. });
  101196. }
  101197. };
  101198. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  101199. /**
  101200. * Gets the image processing configuration used either in this material.
  101201. */
  101202. get: function () {
  101203. return this._imageProcessingConfiguration;
  101204. },
  101205. /**
  101206. * Sets the Default image processing configuration used either in the this material.
  101207. *
  101208. * If sets to null, the scene one is in use.
  101209. */
  101210. set: function (value) {
  101211. this._attachImageProcessingConfiguration(value);
  101212. // Ensure the effect will be rebuilt.
  101213. this._markAllSubMeshesAsTexturesDirty();
  101214. },
  101215. enumerable: true,
  101216. configurable: true
  101217. });
  101218. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  101219. /**
  101220. * Gets wether the color curves effect is enabled.
  101221. */
  101222. get: function () {
  101223. return this.imageProcessingConfiguration.colorCurvesEnabled;
  101224. },
  101225. /**
  101226. * Sets wether the color curves effect is enabled.
  101227. */
  101228. set: function (value) {
  101229. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  101230. },
  101231. enumerable: true,
  101232. configurable: true
  101233. });
  101234. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  101235. /**
  101236. * Gets wether the color grading effect is enabled.
  101237. */
  101238. get: function () {
  101239. return this.imageProcessingConfiguration.colorGradingEnabled;
  101240. },
  101241. /**
  101242. * Gets wether the color grading effect is enabled.
  101243. */
  101244. set: function (value) {
  101245. this.imageProcessingConfiguration.colorGradingEnabled = value;
  101246. },
  101247. enumerable: true,
  101248. configurable: true
  101249. });
  101250. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  101251. /**
  101252. * Gets wether tonemapping is enabled or not.
  101253. */
  101254. get: function () {
  101255. return this._imageProcessingConfiguration.toneMappingEnabled;
  101256. },
  101257. /**
  101258. * Sets wether tonemapping is enabled or not
  101259. */
  101260. set: function (value) {
  101261. this._imageProcessingConfiguration.toneMappingEnabled = value;
  101262. },
  101263. enumerable: true,
  101264. configurable: true
  101265. });
  101266. ;
  101267. ;
  101268. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  101269. /**
  101270. * The camera exposure used on this material.
  101271. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101272. * This corresponds to a photographic exposure.
  101273. */
  101274. get: function () {
  101275. return this._imageProcessingConfiguration.exposure;
  101276. },
  101277. /**
  101278. * The camera exposure used on this material.
  101279. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101280. * This corresponds to a photographic exposure.
  101281. */
  101282. set: function (value) {
  101283. this._imageProcessingConfiguration.exposure = value;
  101284. },
  101285. enumerable: true,
  101286. configurable: true
  101287. });
  101288. ;
  101289. ;
  101290. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  101291. /**
  101292. * Gets The camera contrast used on this material.
  101293. */
  101294. get: function () {
  101295. return this._imageProcessingConfiguration.contrast;
  101296. },
  101297. /**
  101298. * Sets The camera contrast used on this material.
  101299. */
  101300. set: function (value) {
  101301. this._imageProcessingConfiguration.contrast = value;
  101302. },
  101303. enumerable: true,
  101304. configurable: true
  101305. });
  101306. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  101307. /**
  101308. * Gets the Color Grading 2D Lookup Texture.
  101309. */
  101310. get: function () {
  101311. return this._imageProcessingConfiguration.colorGradingTexture;
  101312. },
  101313. /**
  101314. * Sets the Color Grading 2D Lookup Texture.
  101315. */
  101316. set: function (value) {
  101317. this.imageProcessingConfiguration.colorGradingTexture = value;
  101318. },
  101319. enumerable: true,
  101320. configurable: true
  101321. });
  101322. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  101323. /**
  101324. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101325. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101326. * 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;
  101327. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101328. */
  101329. get: function () {
  101330. return this.imageProcessingConfiguration.colorCurves;
  101331. },
  101332. /**
  101333. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101334. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101335. * 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;
  101336. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101337. */
  101338. set: function (value) {
  101339. this.imageProcessingConfiguration.colorCurves = value;
  101340. },
  101341. enumerable: true,
  101342. configurable: true
  101343. });
  101344. /**
  101345. * The entire material has been created in order to prevent overdraw.
  101346. * @returns false
  101347. */
  101348. BackgroundMaterial.prototype.needAlphaTesting = function () {
  101349. return true;
  101350. };
  101351. /**
  101352. * The entire material has been created in order to prevent overdraw.
  101353. * @returns true if blending is enable
  101354. */
  101355. BackgroundMaterial.prototype.needAlphaBlending = function () {
  101356. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  101357. };
  101358. /**
  101359. * Checks wether the material is ready to be rendered for a given mesh.
  101360. * @param mesh The mesh to render
  101361. * @param subMesh The submesh to check against
  101362. * @param useInstances Specify wether or not the material is used with instances
  101363. * @returns true if all the dependencies are ready (Textures, Effects...)
  101364. */
  101365. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  101366. var _this = this;
  101367. if (useInstances === void 0) { useInstances = false; }
  101368. if (subMesh.effect && this.isFrozen) {
  101369. if (this._wasPreviouslyReady) {
  101370. return true;
  101371. }
  101372. }
  101373. if (!subMesh._materialDefines) {
  101374. subMesh._materialDefines = new BackgroundMaterialDefines();
  101375. }
  101376. var scene = this.getScene();
  101377. var defines = subMesh._materialDefines;
  101378. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  101379. if (defines._renderId === scene.getRenderId()) {
  101380. return true;
  101381. }
  101382. }
  101383. var engine = scene.getEngine();
  101384. // Lights
  101385. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  101386. defines._needNormals = true;
  101387. // Textures
  101388. if (defines._areTexturesDirty) {
  101389. defines._needUVs = false;
  101390. if (scene.texturesEnabled) {
  101391. if (scene.getEngine().getCaps().textureLOD) {
  101392. defines.TEXTURELODSUPPORT = true;
  101393. }
  101394. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101395. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  101396. return false;
  101397. }
  101398. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  101399. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  101400. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  101401. defines.OPACITYFRESNEL = this._opacityFresnel;
  101402. }
  101403. else {
  101404. defines.DIFFUSE = false;
  101405. defines.DIFFUSEHASALPHA = false;
  101406. defines.GAMMADIFFUSE = false;
  101407. defines.OPACITYFRESNEL = false;
  101408. }
  101409. var reflectionTexture = this._reflectionTexture;
  101410. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101411. if (!reflectionTexture.isReadyOrNotBlocking()) {
  101412. return false;
  101413. }
  101414. defines.REFLECTION = true;
  101415. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  101416. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  101417. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  101418. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  101419. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  101420. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  101421. defines.REFLECTIONBGR = this.switchToBGR;
  101422. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  101423. defines.INVERTCUBICMAP = true;
  101424. }
  101425. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  101426. switch (reflectionTexture.coordinatesMode) {
  101427. case BABYLON.Texture.EXPLICIT_MODE:
  101428. defines.REFLECTIONMAP_EXPLICIT = true;
  101429. break;
  101430. case BABYLON.Texture.PLANAR_MODE:
  101431. defines.REFLECTIONMAP_PLANAR = true;
  101432. break;
  101433. case BABYLON.Texture.PROJECTION_MODE:
  101434. defines.REFLECTIONMAP_PROJECTION = true;
  101435. break;
  101436. case BABYLON.Texture.SKYBOX_MODE:
  101437. defines.REFLECTIONMAP_SKYBOX = true;
  101438. break;
  101439. case BABYLON.Texture.SPHERICAL_MODE:
  101440. defines.REFLECTIONMAP_SPHERICAL = true;
  101441. break;
  101442. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  101443. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  101444. break;
  101445. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  101446. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  101447. break;
  101448. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  101449. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  101450. break;
  101451. case BABYLON.Texture.CUBIC_MODE:
  101452. case BABYLON.Texture.INVCUBIC_MODE:
  101453. default:
  101454. defines.REFLECTIONMAP_CUBIC = true;
  101455. break;
  101456. }
  101457. if (this.reflectionFresnel) {
  101458. defines.REFLECTIONFRESNEL = true;
  101459. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  101460. this._reflectionControls.x = this.reflectionAmount;
  101461. this._reflectionControls.y = this.reflectionReflectance0;
  101462. this._reflectionControls.z = this.reflectionReflectance90;
  101463. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  101464. }
  101465. else {
  101466. defines.REFLECTIONFRESNEL = false;
  101467. defines.REFLECTIONFALLOFF = false;
  101468. }
  101469. }
  101470. else {
  101471. defines.REFLECTION = false;
  101472. defines.REFLECTIONFRESNEL = false;
  101473. defines.REFLECTIONFALLOFF = false;
  101474. defines.REFLECTIONBLUR = false;
  101475. defines.REFLECTIONMAP_3D = false;
  101476. defines.REFLECTIONMAP_SPHERICAL = false;
  101477. defines.REFLECTIONMAP_PLANAR = false;
  101478. defines.REFLECTIONMAP_CUBIC = false;
  101479. defines.REFLECTIONMAP_PROJECTION = false;
  101480. defines.REFLECTIONMAP_SKYBOX = false;
  101481. defines.REFLECTIONMAP_EXPLICIT = false;
  101482. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101483. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101484. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101485. defines.INVERTCUBICMAP = false;
  101486. defines.REFLECTIONMAP_OPPOSITEZ = false;
  101487. defines.LODINREFLECTIONALPHA = false;
  101488. defines.GAMMAREFLECTION = false;
  101489. defines.RGBDREFLECTION = false;
  101490. }
  101491. }
  101492. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  101493. defines.USERGBCOLOR = this._useRGBColor;
  101494. defines.NOISE = this._enableNoise;
  101495. }
  101496. if (defines._areLightsDirty) {
  101497. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  101498. }
  101499. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  101500. if (!this._imageProcessingConfiguration.isReady()) {
  101501. return false;
  101502. }
  101503. this._imageProcessingConfiguration.prepareDefines(defines);
  101504. }
  101505. // Misc.
  101506. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  101507. // Values that need to be evaluated on every frame
  101508. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  101509. // Attribs
  101510. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  101511. if (mesh) {
  101512. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  101513. mesh.createNormals(true);
  101514. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  101515. }
  101516. }
  101517. }
  101518. // Get correct effect
  101519. if (defines.isDirty) {
  101520. defines.markAsProcessed();
  101521. scene.resetCachedMaterial();
  101522. // Fallbacks
  101523. var fallbacks = new BABYLON.EffectFallbacks();
  101524. if (defines.FOG) {
  101525. fallbacks.addFallback(0, "FOG");
  101526. }
  101527. if (defines.POINTSIZE) {
  101528. fallbacks.addFallback(1, "POINTSIZE");
  101529. }
  101530. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  101531. if (defines.NUM_BONE_INFLUENCERS > 0) {
  101532. fallbacks.addCPUSkinningFallback(0, mesh);
  101533. }
  101534. //Attributes
  101535. var attribs = [BABYLON.VertexBuffer.PositionKind];
  101536. if (defines.NORMAL) {
  101537. attribs.push(BABYLON.VertexBuffer.NormalKind);
  101538. }
  101539. if (defines.UV1) {
  101540. attribs.push(BABYLON.VertexBuffer.UVKind);
  101541. }
  101542. if (defines.UV2) {
  101543. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101544. }
  101545. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  101546. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  101547. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  101548. "vFogInfos", "vFogColor", "pointSize",
  101549. "vClipPlane", "mBones",
  101550. "vPrimaryColor", "vPrimaryColorShadow",
  101551. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  101552. "shadowLevel", "alpha",
  101553. "vBackgroundCenter", "vReflectionControl",
  101554. "vDiffuseInfos", "diffuseMatrix",
  101555. ];
  101556. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  101557. var uniformBuffers = ["Material", "Scene"];
  101558. if (BABYLON.ImageProcessingConfiguration) {
  101559. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  101560. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  101561. }
  101562. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  101563. uniformsNames: uniforms,
  101564. uniformBuffersNames: uniformBuffers,
  101565. samplers: samplers,
  101566. defines: defines,
  101567. maxSimultaneousLights: this._maxSimultaneousLights
  101568. });
  101569. var onCompiled = function (effect) {
  101570. if (_this.onCompiled) {
  101571. _this.onCompiled(effect);
  101572. }
  101573. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  101574. };
  101575. var join = defines.toString();
  101576. subMesh.setEffect(scene.getEngine().createEffect("background", {
  101577. attributes: attribs,
  101578. uniformsNames: uniforms,
  101579. uniformBuffersNames: uniformBuffers,
  101580. samplers: samplers,
  101581. defines: join,
  101582. fallbacks: fallbacks,
  101583. onCompiled: onCompiled,
  101584. onError: this.onError,
  101585. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  101586. }, engine), defines);
  101587. this.buildUniformLayout();
  101588. }
  101589. if (!subMesh.effect || !subMesh.effect.isReady()) {
  101590. return false;
  101591. }
  101592. defines._renderId = scene.getRenderId();
  101593. this._wasPreviouslyReady = true;
  101594. return true;
  101595. };
  101596. /**
  101597. * Compute the primary color according to the chosen perceptual color.
  101598. */
  101599. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  101600. if (!this.__perceptualColor) {
  101601. return;
  101602. }
  101603. this._primaryColor.copyFrom(this.__perceptualColor);
  101604. // Revert gamma space.
  101605. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  101606. // Revert image processing configuration.
  101607. if (this._imageProcessingConfiguration) {
  101608. // Revert Exposure.
  101609. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  101610. }
  101611. this._computePrimaryColors();
  101612. };
  101613. /**
  101614. * Compute the highlights and shadow colors according to their chosen levels.
  101615. */
  101616. BackgroundMaterial.prototype._computePrimaryColors = function () {
  101617. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  101618. return;
  101619. }
  101620. // Find the highlight color based on the configuration.
  101621. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  101622. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  101623. // Find the shadow color based on the configuration.
  101624. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  101625. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  101626. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  101627. };
  101628. /**
  101629. * Build the uniform buffer used in the material.
  101630. */
  101631. BackgroundMaterial.prototype.buildUniformLayout = function () {
  101632. // Order is important !
  101633. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  101634. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  101635. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  101636. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  101637. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  101638. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  101639. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  101640. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  101641. this._uniformBuffer.addUniform("pointSize", 1);
  101642. this._uniformBuffer.addUniform("shadowLevel", 1);
  101643. this._uniformBuffer.addUniform("alpha", 1);
  101644. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  101645. this._uniformBuffer.addUniform("vReflectionControl", 4);
  101646. this._uniformBuffer.create();
  101647. };
  101648. /**
  101649. * Unbind the material.
  101650. */
  101651. BackgroundMaterial.prototype.unbind = function () {
  101652. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  101653. this._uniformBuffer.setTexture("diffuseSampler", null);
  101654. }
  101655. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  101656. this._uniformBuffer.setTexture("reflectionSampler", null);
  101657. }
  101658. _super.prototype.unbind.call(this);
  101659. };
  101660. /**
  101661. * Bind only the world matrix to the material.
  101662. * @param world The world matrix to bind.
  101663. */
  101664. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  101665. this._activeEffect.setMatrix("world", world);
  101666. };
  101667. /**
  101668. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  101669. * @param world The world matrix to bind.
  101670. * @param subMesh The submesh to bind for.
  101671. */
  101672. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  101673. var scene = this.getScene();
  101674. var defines = subMesh._materialDefines;
  101675. if (!defines) {
  101676. return;
  101677. }
  101678. var effect = subMesh.effect;
  101679. if (!effect) {
  101680. return;
  101681. }
  101682. this._activeEffect = effect;
  101683. // Matrices
  101684. this.bindOnlyWorldMatrix(world);
  101685. // Bones
  101686. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  101687. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  101688. if (mustRebind) {
  101689. this._uniformBuffer.bindToEffect(effect, "Material");
  101690. this.bindViewProjection(effect);
  101691. var reflectionTexture = this._reflectionTexture;
  101692. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  101693. // Texture uniforms
  101694. if (scene.texturesEnabled) {
  101695. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101696. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  101697. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  101698. }
  101699. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101700. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  101701. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  101702. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  101703. }
  101704. }
  101705. if (this.shadowLevel > 0) {
  101706. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  101707. }
  101708. this._uniformBuffer.updateFloat("alpha", this.alpha);
  101709. // Point size
  101710. if (this.pointsCloud) {
  101711. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  101712. }
  101713. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  101714. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  101715. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  101716. }
  101717. else {
  101718. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  101719. }
  101720. }
  101721. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  101722. // Textures
  101723. if (scene.texturesEnabled) {
  101724. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101725. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  101726. }
  101727. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101728. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  101729. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101730. }
  101731. else if (!defines.REFLECTIONBLUR) {
  101732. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101733. }
  101734. else {
  101735. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  101736. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  101737. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  101738. }
  101739. if (defines.REFLECTIONFRESNEL) {
  101740. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  101741. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  101742. }
  101743. }
  101744. }
  101745. // Clip plane
  101746. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  101747. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  101748. }
  101749. if (mustRebind || !this.isFrozen) {
  101750. if (scene.lightsEnabled) {
  101751. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  101752. }
  101753. // View
  101754. this.bindView(effect);
  101755. // Fog
  101756. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  101757. // image processing
  101758. if (this._imageProcessingConfiguration) {
  101759. this._imageProcessingConfiguration.bind(this._activeEffect);
  101760. }
  101761. }
  101762. this._uniformBuffer.update();
  101763. this._afterBind(mesh, this._activeEffect);
  101764. };
  101765. /**
  101766. * Dispose the material.
  101767. * @param forceDisposeEffect Force disposal of the associated effect.
  101768. * @param forceDisposeTextures Force disposal of the associated textures.
  101769. */
  101770. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  101771. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  101772. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  101773. if (forceDisposeTextures) {
  101774. if (this.diffuseTexture) {
  101775. this.diffuseTexture.dispose();
  101776. }
  101777. if (this.reflectionTexture) {
  101778. this.reflectionTexture.dispose();
  101779. }
  101780. }
  101781. this._renderTargets.dispose();
  101782. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101783. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101784. }
  101785. _super.prototype.dispose.call(this, forceDisposeEffect);
  101786. };
  101787. /**
  101788. * Clones the material.
  101789. * @param name The cloned name.
  101790. * @returns The cloned material.
  101791. */
  101792. BackgroundMaterial.prototype.clone = function (name) {
  101793. var _this = this;
  101794. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  101795. };
  101796. /**
  101797. * Serializes the current material to its JSON representation.
  101798. * @returns The JSON representation.
  101799. */
  101800. BackgroundMaterial.prototype.serialize = function () {
  101801. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101802. serializationObject.customType = "BABYLON.BackgroundMaterial";
  101803. return serializationObject;
  101804. };
  101805. /**
  101806. * Gets the class name of the material
  101807. * @returns "BackgroundMaterial"
  101808. */
  101809. BackgroundMaterial.prototype.getClassName = function () {
  101810. return "BackgroundMaterial";
  101811. };
  101812. /**
  101813. * Parse a JSON input to create back a background material.
  101814. * @param source The JSON data to parse
  101815. * @param scene The scene to create the parsed material in
  101816. * @param rootUrl The root url of the assets the material depends upon
  101817. * @returns the instantiated BackgroundMaterial.
  101818. */
  101819. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  101820. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  101821. };
  101822. /**
  101823. * Standard reflectance value at parallel view angle.
  101824. */
  101825. BackgroundMaterial.StandardReflectance0 = 0.05;
  101826. /**
  101827. * Standard reflectance value at grazing angle.
  101828. */
  101829. BackgroundMaterial.StandardReflectance90 = 0.5;
  101830. __decorate([
  101831. BABYLON.serializeAsColor3()
  101832. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  101833. __decorate([
  101834. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101835. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  101836. __decorate([
  101837. BABYLON.serializeAsColor3()
  101838. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  101839. __decorate([
  101840. BABYLON.serialize()
  101841. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  101842. __decorate([
  101843. BABYLON.serialize()
  101844. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  101845. __decorate([
  101846. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101847. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  101848. __decorate([
  101849. BABYLON.serializeAsTexture()
  101850. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  101851. __decorate([
  101852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101853. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  101854. __decorate([
  101855. BABYLON.serialize()
  101856. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  101857. __decorate([
  101858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101859. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  101860. __decorate([
  101861. BABYLON.serializeAsTexture()
  101862. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  101863. __decorate([
  101864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101865. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  101866. __decorate([
  101867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101868. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  101869. __decorate([
  101870. BABYLON.serialize()
  101871. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  101872. __decorate([
  101873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101874. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  101875. __decorate([
  101876. BABYLON.serializeAsVector3()
  101877. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  101878. __decorate([
  101879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101880. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  101881. __decorate([
  101882. BABYLON.serialize()
  101883. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  101884. __decorate([
  101885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101886. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  101887. __decorate([
  101888. BABYLON.serialize()
  101889. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  101890. __decorate([
  101891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101892. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  101893. __decorate([
  101894. BABYLON.serialize()
  101895. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  101896. __decorate([
  101897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101898. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  101899. __decorate([
  101900. BABYLON.serialize()
  101901. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  101902. __decorate([
  101903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101904. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  101905. __decorate([
  101906. BABYLON.serialize()
  101907. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  101908. __decorate([
  101909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101910. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  101911. __decorate([
  101912. BABYLON.serialize()
  101913. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  101914. __decorate([
  101915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101916. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  101917. __decorate([
  101918. BABYLON.serialize()
  101919. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  101920. __decorate([
  101921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101922. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  101923. __decorate([
  101924. BABYLON.serialize()
  101925. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  101926. __decorate([
  101927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101928. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  101929. __decorate([
  101930. BABYLON.serialize()
  101931. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  101932. __decorate([
  101933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101934. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  101935. __decorate([
  101936. BABYLON.serializeAsImageProcessingConfiguration()
  101937. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  101938. return BackgroundMaterial;
  101939. }(BABYLON.PushMaterial));
  101940. BABYLON.BackgroundMaterial = BackgroundMaterial;
  101941. })(BABYLON || (BABYLON = {}));
  101942. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  101943. var __assign = (this && this.__assign) || Object.assign || function(t) {
  101944. for (var s, i = 1, n = arguments.length; i < n; i++) {
  101945. s = arguments[i];
  101946. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  101947. t[p] = s[p];
  101948. }
  101949. return t;
  101950. };
  101951. var BABYLON;
  101952. (function (BABYLON) {
  101953. /**
  101954. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  101955. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  101956. * It also helps with the default setup of your imageProcessing configuration.
  101957. */
  101958. var EnvironmentHelper = /** @class */ (function () {
  101959. /**
  101960. * constructor
  101961. * @param options
  101962. * @param scene The scene to add the material to
  101963. */
  101964. function EnvironmentHelper(options, scene) {
  101965. var _this = this;
  101966. this._errorHandler = function (message, exception) {
  101967. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  101968. };
  101969. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  101970. this._scene = scene;
  101971. this.onErrorObservable = new BABYLON.Observable();
  101972. this._setupBackground();
  101973. this._setupImageProcessing();
  101974. }
  101975. /**
  101976. * Creates the default options for the helper.
  101977. */
  101978. EnvironmentHelper._getDefaultOptions = function () {
  101979. return {
  101980. createGround: true,
  101981. groundSize: 15,
  101982. groundTexture: this._groundTextureCDNUrl,
  101983. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101984. groundOpacity: 0.9,
  101985. enableGroundShadow: true,
  101986. groundShadowLevel: 0.5,
  101987. enableGroundMirror: false,
  101988. groundMirrorSizeRatio: 0.3,
  101989. groundMirrorBlurKernel: 64,
  101990. groundMirrorAmount: 1,
  101991. groundMirrorFresnelWeight: 1,
  101992. groundMirrorFallOffDistance: 0,
  101993. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  101994. groundYBias: 0.00001,
  101995. createSkybox: true,
  101996. skyboxSize: 20,
  101997. skyboxTexture: this._skyboxTextureCDNUrl,
  101998. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101999. backgroundYRotation: 0,
  102000. sizeAuto: true,
  102001. rootPosition: BABYLON.Vector3.Zero(),
  102002. setupImageProcessing: true,
  102003. environmentTexture: this._environmentTextureCDNUrl,
  102004. cameraExposure: 0.8,
  102005. cameraContrast: 1.2,
  102006. toneMappingEnabled: true,
  102007. };
  102008. };
  102009. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102010. /**
  102011. * Gets the root mesh created by the helper.
  102012. */
  102013. get: function () {
  102014. return this._rootMesh;
  102015. },
  102016. enumerable: true,
  102017. configurable: true
  102018. });
  102019. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102020. /**
  102021. * Gets the skybox created by the helper.
  102022. */
  102023. get: function () {
  102024. return this._skybox;
  102025. },
  102026. enumerable: true,
  102027. configurable: true
  102028. });
  102029. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  102030. /**
  102031. * Gets the skybox texture created by the helper.
  102032. */
  102033. get: function () {
  102034. return this._skyboxTexture;
  102035. },
  102036. enumerable: true,
  102037. configurable: true
  102038. });
  102039. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  102040. /**
  102041. * Gets the skybox material created by the helper.
  102042. */
  102043. get: function () {
  102044. return this._skyboxMaterial;
  102045. },
  102046. enumerable: true,
  102047. configurable: true
  102048. });
  102049. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  102050. /**
  102051. * Gets the ground mesh created by the helper.
  102052. */
  102053. get: function () {
  102054. return this._ground;
  102055. },
  102056. enumerable: true,
  102057. configurable: true
  102058. });
  102059. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  102060. /**
  102061. * Gets the ground texture created by the helper.
  102062. */
  102063. get: function () {
  102064. return this._groundTexture;
  102065. },
  102066. enumerable: true,
  102067. configurable: true
  102068. });
  102069. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  102070. /**
  102071. * Gets the ground mirror created by the helper.
  102072. */
  102073. get: function () {
  102074. return this._groundMirror;
  102075. },
  102076. enumerable: true,
  102077. configurable: true
  102078. });
  102079. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  102080. /**
  102081. * Gets the ground mirror render list to helps pushing the meshes
  102082. * you wish in the ground reflection.
  102083. */
  102084. get: function () {
  102085. if (this._groundMirror) {
  102086. return this._groundMirror.renderList;
  102087. }
  102088. return null;
  102089. },
  102090. enumerable: true,
  102091. configurable: true
  102092. });
  102093. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  102094. /**
  102095. * Gets the ground material created by the helper.
  102096. */
  102097. get: function () {
  102098. return this._groundMaterial;
  102099. },
  102100. enumerable: true,
  102101. configurable: true
  102102. });
  102103. /**
  102104. * Updates the background according to the new options
  102105. * @param options
  102106. */
  102107. EnvironmentHelper.prototype.updateOptions = function (options) {
  102108. var newOptions = __assign({}, this._options, options);
  102109. if (this._ground && !newOptions.createGround) {
  102110. this._ground.dispose();
  102111. this._ground = null;
  102112. }
  102113. if (this._groundMaterial && !newOptions.createGround) {
  102114. this._groundMaterial.dispose();
  102115. this._groundMaterial = null;
  102116. }
  102117. if (this._groundTexture) {
  102118. if (this._options.groundTexture != newOptions.groundTexture) {
  102119. this._groundTexture.dispose();
  102120. this._groundTexture = null;
  102121. }
  102122. }
  102123. if (this._skybox && !newOptions.createSkybox) {
  102124. this._skybox.dispose();
  102125. this._skybox = null;
  102126. }
  102127. if (this._skyboxMaterial && !newOptions.createSkybox) {
  102128. this._skyboxMaterial.dispose();
  102129. this._skyboxMaterial = null;
  102130. }
  102131. if (this._skyboxTexture) {
  102132. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  102133. this._skyboxTexture.dispose();
  102134. this._skyboxTexture = null;
  102135. }
  102136. }
  102137. if (this._groundMirror && !newOptions.enableGroundMirror) {
  102138. this._groundMirror.dispose();
  102139. this._groundMirror = null;
  102140. }
  102141. if (this._scene.environmentTexture) {
  102142. if (this._options.environmentTexture != newOptions.environmentTexture) {
  102143. this._scene.environmentTexture.dispose();
  102144. }
  102145. }
  102146. this._options = newOptions;
  102147. this._setupBackground();
  102148. this._setupImageProcessing();
  102149. };
  102150. /**
  102151. * Sets the primary color of all the available elements.
  102152. * @param color the main color to affect to the ground and the background
  102153. */
  102154. EnvironmentHelper.prototype.setMainColor = function (color) {
  102155. if (this.groundMaterial) {
  102156. this.groundMaterial.primaryColor = color;
  102157. }
  102158. if (this.skyboxMaterial) {
  102159. this.skyboxMaterial.primaryColor = color;
  102160. }
  102161. if (this.groundMirror) {
  102162. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  102163. }
  102164. };
  102165. /**
  102166. * Setup the image processing according to the specified options.
  102167. */
  102168. EnvironmentHelper.prototype._setupImageProcessing = function () {
  102169. if (this._options.setupImageProcessing) {
  102170. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  102171. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  102172. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  102173. this._setupEnvironmentTexture();
  102174. }
  102175. };
  102176. /**
  102177. * Setup the environment texture according to the specified options.
  102178. */
  102179. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  102180. if (this._scene.environmentTexture) {
  102181. return;
  102182. }
  102183. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  102184. this._scene.environmentTexture = this._options.environmentTexture;
  102185. return;
  102186. }
  102187. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  102188. this._scene.environmentTexture = environmentTexture;
  102189. };
  102190. /**
  102191. * Setup the background according to the specified options.
  102192. */
  102193. EnvironmentHelper.prototype._setupBackground = function () {
  102194. if (!this._rootMesh) {
  102195. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  102196. }
  102197. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  102198. var sceneSize = this._getSceneSize();
  102199. if (this._options.createGround) {
  102200. this._setupGround(sceneSize);
  102201. this._setupGroundMaterial();
  102202. this._setupGroundDiffuseTexture();
  102203. if (this._options.enableGroundMirror) {
  102204. this._setupGroundMirrorTexture(sceneSize);
  102205. }
  102206. this._setupMirrorInGroundMaterial();
  102207. }
  102208. if (this._options.createSkybox) {
  102209. this._setupSkybox(sceneSize);
  102210. this._setupSkyboxMaterial();
  102211. this._setupSkyboxReflectionTexture();
  102212. }
  102213. this._rootMesh.position.x = sceneSize.rootPosition.x;
  102214. this._rootMesh.position.z = sceneSize.rootPosition.z;
  102215. this._rootMesh.position.y = sceneSize.rootPosition.y;
  102216. };
  102217. /**
  102218. * Get the scene sizes according to the setup.
  102219. */
  102220. EnvironmentHelper.prototype._getSceneSize = function () {
  102221. var _this = this;
  102222. var groundSize = this._options.groundSize;
  102223. var skyboxSize = this._options.skyboxSize;
  102224. var rootPosition = this._options.rootPosition;
  102225. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  102226. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102227. }
  102228. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  102229. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  102230. });
  102231. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  102232. if (this._options.sizeAuto) {
  102233. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  102234. this._scene.activeCamera.upperRadiusLimit) {
  102235. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  102236. skyboxSize = groundSize;
  102237. }
  102238. var sceneDiagonalLenght = sceneDiagonal.length();
  102239. if (sceneDiagonalLenght > groundSize) {
  102240. groundSize = sceneDiagonalLenght * 2;
  102241. skyboxSize = groundSize;
  102242. }
  102243. // 10 % bigger.
  102244. groundSize *= 1.1;
  102245. skyboxSize *= 1.5;
  102246. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  102247. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  102248. }
  102249. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102250. };
  102251. /**
  102252. * Setup the ground according to the specified options.
  102253. */
  102254. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  102255. var _this = this;
  102256. if (!this._ground || this._ground.isDisposed()) {
  102257. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  102258. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  102259. this._ground.parent = this._rootMesh;
  102260. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  102261. }
  102262. this._ground.receiveShadows = this._options.enableGroundShadow;
  102263. };
  102264. /**
  102265. * Setup the ground material according to the specified options.
  102266. */
  102267. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  102268. if (!this._groundMaterial) {
  102269. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  102270. }
  102271. this._groundMaterial.alpha = this._options.groundOpacity;
  102272. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  102273. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  102274. this._groundMaterial.primaryColor = this._options.groundColor;
  102275. this._groundMaterial.useRGBColor = false;
  102276. this._groundMaterial.enableNoise = true;
  102277. if (this._ground) {
  102278. this._ground.material = this._groundMaterial;
  102279. }
  102280. };
  102281. /**
  102282. * Setup the ground diffuse texture according to the specified options.
  102283. */
  102284. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  102285. if (!this._groundMaterial) {
  102286. return;
  102287. }
  102288. if (this._groundTexture) {
  102289. return;
  102290. }
  102291. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  102292. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  102293. return;
  102294. }
  102295. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102296. diffuseTexture.gammaSpace = false;
  102297. diffuseTexture.hasAlpha = true;
  102298. this._groundMaterial.diffuseTexture = diffuseTexture;
  102299. };
  102300. /**
  102301. * Setup the ground mirror texture according to the specified options.
  102302. */
  102303. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  102304. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102305. if (!this._groundMirror) {
  102306. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  102307. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  102308. this._groundMirror.anisotropicFilteringLevel = 1;
  102309. this._groundMirror.wrapU = wrapping;
  102310. this._groundMirror.wrapV = wrapping;
  102311. this._groundMirror.gammaSpace = false;
  102312. if (this._groundMirror.renderList) {
  102313. for (var i = 0; i < this._scene.meshes.length; i++) {
  102314. var mesh = this._scene.meshes[i];
  102315. if (mesh !== this._ground &&
  102316. mesh !== this._skybox &&
  102317. mesh !== this._rootMesh) {
  102318. this._groundMirror.renderList.push(mesh);
  102319. }
  102320. }
  102321. }
  102322. }
  102323. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  102324. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  102325. };
  102326. /**
  102327. * Setup the ground to receive the mirror texture.
  102328. */
  102329. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  102330. if (this._groundMaterial) {
  102331. this._groundMaterial.reflectionTexture = this._groundMirror;
  102332. this._groundMaterial.reflectionFresnel = true;
  102333. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  102334. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  102335. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  102336. }
  102337. };
  102338. /**
  102339. * Setup the skybox according to the specified options.
  102340. */
  102341. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  102342. var _this = this;
  102343. if (!this._skybox || this._skybox.isDisposed()) {
  102344. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  102345. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  102346. }
  102347. this._skybox.parent = this._rootMesh;
  102348. };
  102349. /**
  102350. * Setup the skybox material according to the specified options.
  102351. */
  102352. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  102353. if (!this._skybox) {
  102354. return;
  102355. }
  102356. if (!this._skyboxMaterial) {
  102357. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  102358. }
  102359. this._skyboxMaterial.useRGBColor = false;
  102360. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  102361. this._skyboxMaterial.enableNoise = true;
  102362. this._skybox.material = this._skyboxMaterial;
  102363. };
  102364. /**
  102365. * Setup the skybox reflection texture according to the specified options.
  102366. */
  102367. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  102368. if (!this._skyboxMaterial) {
  102369. return;
  102370. }
  102371. if (this._skyboxTexture) {
  102372. return;
  102373. }
  102374. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  102375. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  102376. return;
  102377. }
  102378. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102379. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  102380. this._skyboxTexture.gammaSpace = false;
  102381. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  102382. };
  102383. /**
  102384. * Dispose all the elements created by the Helper.
  102385. */
  102386. EnvironmentHelper.prototype.dispose = function () {
  102387. if (this._groundMaterial) {
  102388. this._groundMaterial.dispose(true, true);
  102389. }
  102390. if (this._skyboxMaterial) {
  102391. this._skyboxMaterial.dispose(true, true);
  102392. }
  102393. this._rootMesh.dispose(false);
  102394. };
  102395. /**
  102396. * Default ground texture URL.
  102397. */
  102398. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  102399. /**
  102400. * Default skybox texture URL.
  102401. */
  102402. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  102403. /**
  102404. * Default environment texture URL.
  102405. */
  102406. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  102407. return EnvironmentHelper;
  102408. }());
  102409. BABYLON.EnvironmentHelper = EnvironmentHelper;
  102410. })(BABYLON || (BABYLON = {}));
  102411. //# sourceMappingURL=babylon.environmentHelper.js.map
  102412. var BABYLON;
  102413. (function (BABYLON) {
  102414. /** Internal class used to store shapes for emitters */
  102415. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  102416. function ParticleSystemSetEmitterCreationOptions() {
  102417. }
  102418. return ParticleSystemSetEmitterCreationOptions;
  102419. }());
  102420. /**
  102421. * Represents a set of particle systems working together to create a specific effect
  102422. */
  102423. var ParticleSystemSet = /** @class */ (function () {
  102424. function ParticleSystemSet() {
  102425. /**
  102426. * Gets the particle system list
  102427. */
  102428. this.systems = new Array();
  102429. }
  102430. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  102431. /**
  102432. * Gets the emitter node used with this set
  102433. */
  102434. get: function () {
  102435. return this._emitterNode;
  102436. },
  102437. enumerable: true,
  102438. configurable: true
  102439. });
  102440. /**
  102441. * Creates a new emitter mesh as a sphere
  102442. * @param options defines the options used to create the sphere
  102443. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  102444. * @param scene defines the hosting scene
  102445. */
  102446. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  102447. if (this._emitterNode) {
  102448. this._emitterNode.dispose();
  102449. }
  102450. this._emitterCreationOptions = {
  102451. kind: "Sphere",
  102452. options: options,
  102453. renderingGroupId: renderingGroupId
  102454. };
  102455. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  102456. emitterMesh.renderingGroupId = renderingGroupId;
  102457. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  102458. material.emissiveColor = options.color;
  102459. emitterMesh.material = material;
  102460. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102461. var system = _a[_i];
  102462. system.emitter = emitterMesh;
  102463. }
  102464. this._emitterNode = emitterMesh;
  102465. };
  102466. /**
  102467. * Starts all particle systems of the set
  102468. * @param emitter defines an optional mesh to use as emitter for the particle systems
  102469. */
  102470. ParticleSystemSet.prototype.start = function (emitter) {
  102471. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102472. var system = _a[_i];
  102473. if (emitter) {
  102474. system.emitter = emitter;
  102475. }
  102476. system.start();
  102477. }
  102478. };
  102479. /**
  102480. * Release all associated resources
  102481. */
  102482. ParticleSystemSet.prototype.dispose = function () {
  102483. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102484. var system = _a[_i];
  102485. system.dispose();
  102486. }
  102487. this.systems = [];
  102488. if (this._emitterNode) {
  102489. this._emitterNode.dispose();
  102490. this._emitterNode = null;
  102491. }
  102492. };
  102493. /**
  102494. * Serialize the set into a JSON compatible object
  102495. * @returns a JSON compatible representation of the set
  102496. */
  102497. ParticleSystemSet.prototype.serialize = function () {
  102498. var result = {};
  102499. result.systems = [];
  102500. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102501. var system = _a[_i];
  102502. result.systems.push(system.serialize());
  102503. }
  102504. if (this._emitterNode) {
  102505. result.emitter = this._emitterCreationOptions;
  102506. }
  102507. return result;
  102508. };
  102509. /**
  102510. * Parse a new ParticleSystemSet from a serialized source
  102511. * @param data defines a JSON compatible representation of the set
  102512. * @param scene defines the hosting scene
  102513. * @param gpu defines if we want GPU particles or CPU particles
  102514. * @returns a new ParticleSystemSet
  102515. */
  102516. ParticleSystemSet.Parse = function (data, scene, gpu) {
  102517. if (gpu === void 0) { gpu = false; }
  102518. var result = new ParticleSystemSet();
  102519. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  102520. scene = scene || BABYLON.Engine.LastCreatedScene;
  102521. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  102522. var system = _a[_i];
  102523. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  102524. }
  102525. if (data.emitter) {
  102526. var options = data.emitter.options;
  102527. switch (data.emitter.kind) {
  102528. case "Sphere":
  102529. result.setEmitterAsSphere({
  102530. diameter: options.diameter,
  102531. segments: options.segments,
  102532. color: BABYLON.Color3.FromArray(options.color)
  102533. }, data.emitter.renderingGroupId, scene);
  102534. break;
  102535. }
  102536. }
  102537. return result;
  102538. };
  102539. return ParticleSystemSet;
  102540. }());
  102541. BABYLON.ParticleSystemSet = ParticleSystemSet;
  102542. })(BABYLON || (BABYLON = {}));
  102543. //# sourceMappingURL=babylon.particleSystemSet.js.map
  102544. var BABYLON;
  102545. (function (BABYLON) {
  102546. /**
  102547. * This class is made for on one-liner static method to help creating particle system set.
  102548. */
  102549. var ParticleHelper = /** @class */ (function () {
  102550. function ParticleHelper() {
  102551. }
  102552. /**
  102553. * This is the main static method (one-liner) of this helper to create different particle systems
  102554. * @param type This string represents the type to the particle system to create
  102555. * @param scene The scene where the particle system should live
  102556. * @param gpu If the system will use gpu
  102557. * @returns the ParticleSystemSet created
  102558. */
  102559. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  102560. if (gpu === void 0) { gpu = false; }
  102561. if (!scene) {
  102562. scene = BABYLON.Engine.LastCreatedScene;
  102563. ;
  102564. }
  102565. var token = {};
  102566. scene._addPendingData(token);
  102567. return new Promise(function (resolve, reject) {
  102568. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  102569. scene._removePendingData(token);
  102570. return reject("Particle system with GPU is not supported.");
  102571. }
  102572. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  102573. scene._removePendingData(token);
  102574. var newData = JSON.parse(data.toString());
  102575. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  102576. }, undefined, undefined, undefined, function (req, exception) {
  102577. scene._removePendingData(token);
  102578. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  102579. });
  102580. });
  102581. };
  102582. /**
  102583. * Static function used to export a particle system to a ParticleSystemSet variable.
  102584. * Please note that the emitter shape is not exported
  102585. * @param system defines the particle systems to export
  102586. */
  102587. ParticleHelper.ExportSet = function (systems) {
  102588. var set = new BABYLON.ParticleSystemSet();
  102589. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  102590. var system = systems_1[_i];
  102591. set.systems.push(system);
  102592. }
  102593. return set;
  102594. };
  102595. /**
  102596. * Gets or sets base Assets URL
  102597. */
  102598. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  102599. return ParticleHelper;
  102600. }());
  102601. BABYLON.ParticleHelper = ParticleHelper;
  102602. })(BABYLON || (BABYLON = {}));
  102603. //# sourceMappingURL=babylon.particleHelper.js.map
  102604. var BABYLON;
  102605. (function (BABYLON) {
  102606. /**
  102607. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  102608. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  102609. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  102610. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102611. */
  102612. var VideoDome = /** @class */ (function (_super) {
  102613. __extends(VideoDome, _super);
  102614. /**
  102615. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  102616. * @param name Element's name, child elements will append suffixes for their own names.
  102617. * @param urlsOrVideo defines the url(s) or the video element to use
  102618. * @param options An object containing optional or exposed sub element properties
  102619. */
  102620. function VideoDome(name, urlsOrVideo, options, scene) {
  102621. var _this = _super.call(this, name, scene) || this;
  102622. _this._useDirectMapping = false;
  102623. // set defaults and manage values
  102624. name = name || "videoDome";
  102625. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102626. options.clickToPlay = Boolean(options.clickToPlay);
  102627. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  102628. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  102629. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102630. if (options.useDirectMapping === undefined) {
  102631. _this._useDirectMapping = true;
  102632. }
  102633. else {
  102634. _this._useDirectMapping = options.useDirectMapping;
  102635. }
  102636. // create
  102637. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  102638. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102639. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  102640. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102641. // configure material
  102642. material.useEquirectangularFOV = true;
  102643. material.fovMultiplier = 1.0;
  102644. material.opacityFresnel = false;
  102645. if (_this._useDirectMapping) {
  102646. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102647. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102648. material.diffuseTexture = texture;
  102649. }
  102650. else {
  102651. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102652. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102653. material.reflectionTexture = texture;
  102654. }
  102655. // configure mesh
  102656. _this._mesh.material = material;
  102657. _this._mesh.parent = _this;
  102658. // optional configuration
  102659. if (options.clickToPlay) {
  102660. scene.onPointerUp = function () {
  102661. _this._videoTexture.video.play();
  102662. };
  102663. }
  102664. return _this;
  102665. }
  102666. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  102667. /**
  102668. * Gets the video texture being displayed on the sphere
  102669. */
  102670. get: function () {
  102671. return this._videoTexture;
  102672. },
  102673. enumerable: true,
  102674. configurable: true
  102675. });
  102676. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  102677. /**
  102678. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102679. * Also see the options.resolution property.
  102680. */
  102681. get: function () {
  102682. return this._material.fovMultiplier;
  102683. },
  102684. set: function (value) {
  102685. this._material.fovMultiplier = value;
  102686. },
  102687. enumerable: true,
  102688. configurable: true
  102689. });
  102690. /**
  102691. * Releases resources associated with this node.
  102692. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102693. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102694. */
  102695. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102696. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102697. this._videoTexture.dispose();
  102698. this._mesh.dispose();
  102699. this._material.dispose();
  102700. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102701. };
  102702. return VideoDome;
  102703. }(BABYLON.Node));
  102704. BABYLON.VideoDome = VideoDome;
  102705. })(BABYLON || (BABYLON = {}));
  102706. //# sourceMappingURL=babylon.videoDome.js.map
  102707. var BABYLON;
  102708. (function (BABYLON) {
  102709. /**
  102710. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  102711. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  102712. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  102713. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102714. */
  102715. var PhotoDome = /** @class */ (function (_super) {
  102716. __extends(PhotoDome, _super);
  102717. /**
  102718. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  102719. * @param name Element's name, child elements will append suffixes for their own names.
  102720. * @param urlsOfPhoto define the url of the photo to display
  102721. * @param options An object containing optional or exposed sub element properties
  102722. */
  102723. function PhotoDome(name, urlOfPhoto, options, scene) {
  102724. var _this = _super.call(this, name, scene) || this;
  102725. _this._useDirectMapping = false;
  102726. // set defaults and manage values
  102727. name = name || "photoDome";
  102728. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102729. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102730. if (options.useDirectMapping === undefined) {
  102731. _this._useDirectMapping = true;
  102732. }
  102733. else {
  102734. _this._useDirectMapping = options.useDirectMapping;
  102735. }
  102736. // create
  102737. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102738. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102739. // configure material
  102740. material.opacityFresnel = false;
  102741. material.useEquirectangularFOV = true;
  102742. material.fovMultiplier = 1.0;
  102743. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  102744. // configure mesh
  102745. _this._mesh.material = material;
  102746. _this._mesh.parent = _this;
  102747. return _this;
  102748. }
  102749. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  102750. /**
  102751. * Gets or sets the texture being displayed on the sphere
  102752. */
  102753. get: function () {
  102754. return this._photoTexture;
  102755. },
  102756. set: function (value) {
  102757. if (this._photoTexture === value) {
  102758. return;
  102759. }
  102760. this._photoTexture = value;
  102761. if (this._useDirectMapping) {
  102762. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102763. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102764. this._material.diffuseTexture = this._photoTexture;
  102765. }
  102766. else {
  102767. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102768. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102769. this._material.reflectionTexture = this._photoTexture;
  102770. }
  102771. },
  102772. enumerable: true,
  102773. configurable: true
  102774. });
  102775. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  102776. /**
  102777. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102778. * Also see the options.resolution property.
  102779. */
  102780. get: function () {
  102781. return this._material.fovMultiplier;
  102782. },
  102783. set: function (value) {
  102784. this._material.fovMultiplier = value;
  102785. },
  102786. enumerable: true,
  102787. configurable: true
  102788. });
  102789. /**
  102790. * Releases resources associated with this node.
  102791. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102792. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102793. */
  102794. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102795. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102796. this._photoTexture.dispose();
  102797. this._mesh.dispose();
  102798. this._material.dispose();
  102799. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102800. };
  102801. return PhotoDome;
  102802. }(BABYLON.Node));
  102803. BABYLON.PhotoDome = PhotoDome;
  102804. })(BABYLON || (BABYLON = {}));
  102805. //# sourceMappingURL=babylon.photoDome.js.map
  102806. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\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<helperFunctions>\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>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\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#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\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\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\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#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\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#ifdef ALPHATEST\nuniform float alphaCutOff;\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>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\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<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\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) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\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;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\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;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\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;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\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#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\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\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\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<helperFunctions>\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(USESPHERICALINVERTEX)\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\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\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) || defined(SPECULARAA)\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(USESPHERICALINVERTEX)\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#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\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\nnormalW*=sign(dot(normalW,faceNormal));\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#include<depthPrePass>\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#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\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;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\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#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,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);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\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.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=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;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=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 RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\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.rgb*=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\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.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\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#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\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\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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\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 float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\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}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\nout vec2 outAngle;\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(age/life,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\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 vec3 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.z*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","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=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\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,depthSign);\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(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\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);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\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}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\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);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/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;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\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#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\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{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\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#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying 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":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=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}","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)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,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#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\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\n#include<logDepthDeclaration>\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#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\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}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\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#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\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\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","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\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#endif\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\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\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 TEXTURELODSUPPORT\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\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\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#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\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#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  102807. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","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 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\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}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\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}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\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#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{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}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\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 PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\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 vec2 vTangentSpaceParams;\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#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \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;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\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 vTangentSpaceParams;\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 computeShadowWithPoissonSamplingCube(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 computeShadowWithPoissonSampling(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#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\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":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\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\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\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;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\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#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\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 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\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\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (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,geometricRoughnessFactor,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,geometricRoughnessFactor,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,geometricRoughnessFactor,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#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\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#elif defined(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#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,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#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\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\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 vec2 vTangentSpaceParams;\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#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\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 vReflectionPosition;\nuniform vec3 vReflectionSize; \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 vec2 vTangentSpaceParams;\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,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\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 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\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","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  102808. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  102809. globalObject["BABYLON"] = BABYLON;
  102810. //backwards compatibility
  102811. if(typeof earcut !== 'undefined') {
  102812. globalObject["Earcut"] = {
  102813. earcut: earcut
  102814. };
  102815. }
  102816. return BABYLON;
  102817. });